using end in array

3 visualizzazioni (ultimi 30 giorni)
NA
NA il 23 Mar 2020
Commentato: Sriram Tadavarty il 23 Mar 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];

Risposta accettata

Sriram Tadavarty
Sriram Tadavarty il 23 Mar 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 Commenti
Sriram Tadavarty
Sriram Tadavarty il 23 Mar 2020
Modificato: Sriram Tadavarty il 23 Mar 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 il 23 Mar 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

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by