Filter löschen
Filter löschen

using end in array

3 Ansichten (letzte 30 Tage)
NA
NA am 23 Mär. 2020
Kommentiert: Sriram Tadavarty am 23 Mär. 2020
I have
B=[];
A = {[1,2,3,15],[14,15,45,44,38,48,47,46]};
for i=1:length(A)
for j=1: length(A{i})-1
temp = A{i};
B =[B;[temp(j), temp(j+1)]];
end
end
B should be
B =[1,2; 2,3; 3,15; 15,1; 14,15; 15,45; 45,44; 44,38;38,47; 47,46; 46 14];

Akzeptierte Antwort

Sriram Tadavarty
Sriram Tadavarty am 23 Mär. 2020
Hi Na,
Minor update to your code, will give what you are looking for
B=[];
A = {[1,2,3,15],[14,15,45,44,38,48,47,46]};
for i=1:length(A)
for j=1: length(A{i})-1
temp = A{i};
B =[B;[temp(j), temp(j+1)]];
end
B = [B; [temp(end), temp(1)]]; % Update this, to get what you are looking for
end
Hope this helps
Regards,
Sriram
  3 Kommentare
Sriram Tadavarty
Sriram Tadavarty am 23 Mär. 2020
Bearbeitet: Sriram Tadavarty am 23 Mär. 2020
Yes you could remove the inner for loop
B=[];
A = {[1,2,3,15],[14,15,45,44,38,48,47,46]};
for i=1:length(A)
temp = [A{i} A{i}(1)];
B = [B;[temp(1:end-1)' temp(2:end)']];
end
Sriram Tadavarty
Sriram Tadavarty am 23 Mär. 2020
Hi,
You can even try this
A = {[1,2,3,15],[14,15,45,44,38,48,47,46]};
ATemp = arrayfun(@(x) [A{x} A{x}(1)],1:length(A),'UniformOutput',false);
BTemp = cellfun(@(x) [x(1:end-1)' x(2:end)'],ATemp,'UniformOutput',false)
B = cell2mat(reshape(BTemp,[],1))
Hope this helps.
Regards,
Sriram

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by