using end in array

3 views (last 30 days)
NA
NA on 23 Mar 2020
Commented: Sriram Tadavarty on 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];

Accepted Answer

Sriram Tadavarty
Sriram Tadavarty on 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 Comments
Sriram Tadavarty
Sriram Tadavarty on 23 Mar 2020
Edited: Sriram Tadavarty on 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 on 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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!