Elementary question, for loop implementation
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
madhan ravi
2018-11-17
编辑:madhan ravi
2018-11-17
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)
回答(1 个)
Guillaume
2018-11-17
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!