Elementary question, for loop implementation
조회 수: 8 (최근 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!