Elementary question, for loop implementation
6 views (last 30 days)
Show older comments
I need to implement "for" loop:
I have 5 matrices, m1,m2,m3,m4,m5 of size 2x3.
in first for loop:
A=m1 (size 2x3)
B=[m2,m3,m4,m5 as they joined together, size 2x12]
in second loop
A=m2
B=[m1,m3,m4,m5]
and so on
(Basically, each time A is one of matrices, B is remaining matrices)
1 Comment
madhan ravi
on 17 Nov 2018
Edited: madhan ravi
on 17 Nov 2018
please don't post the same question again and again (https://www.mathworks.com/matlabcentral/answers/430460-easy-for-loop-implementation-cell-array#comment_638812)
Answers (1)
Guillaume
on 17 Nov 2018
As we've just said in your previous question, do not create numbered arrays. It's always the wrong approach, as you can see now, it's very hard to work with.
Instead of 5 matrices of size 2x3 you should either have a single 2x3x5 matrix or a 1x5 cell array of 2x3 matrices. Whichever you prefer. Either way, your loop is then very easy to write:
%with a single 2x3x5 matrix called m
%note that the code works with any size matrix. It makes no assumption about their size
for i - 1:size(m, 3)
A = m(: :, i);
B = m(:, :, [1:i-1, i+1:end]);
B = reshape(permute(B, [2 3 1]), [], size(B, 1)).'
%do something with A and B
end
%with a single 1x5 cell array of matrices
%note that the code works for any size cell array and matrices, as long as all the matrices are the same size
for i = 1:numel(C)
A = C{i};
B = [C{[1:i-1, i+1:end]}];
end
If for some reason, you cannot change the way you create these numbered variables, you can remediate the problem after the fact with:
m = cat(3, m1, m2, m3, m4, m5); %for a 3d matrix
m = {m1, m2, m3, m4, m5}; %for a cell array
0 Comments
See Also
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!