Elementary question, for loop implementation

조회 수: 8 (최근 30일)
Aydin Ahmadli
Aydin Ahmadli 2018년 11월 17일
답변: Guillaume 2018년 11월 17일
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개)

Guillaume
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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by