'n' number of nested for loops

조회 수: 6 (최근 30일)
Fawad Farooq Ashraf
Fawad Farooq Ashraf 2021년 3월 14일
편집: Matt J 2021년 3월 14일
I have a cell array M with 4 cell elements and each cell element has a 8x2 matrix.
I'm trying to making different combinations using nested for loops as
n = length(M);
[s,d] = cellfun(@size,M);
ncombs = prod(s);
P = cell(1,ncombs);
k = 0;
for i = 1:size(M{1},1)
for j = 1:size(M{2},1)
for x = 1:size(M{3},1)
for y = 1:size(M{4},1)
k = k+1;
P{k} = [M{1}(i,:);M{2}(j,:);M{3}(x,:);M{4}(y,:)];
end
end
end
end
Now in this case, I have n = 4 and hence 4 nested loops. Can I generalize this thing with any n? For example like for n = 2, 2 nested loops and correspondingly P{k} becomes [M{1}(i,:),M{2}(j,:)]
  댓글 수: 2
Matt J
Matt J 2021년 3월 14일
I have a cell array M with 4 cell elements and each cell element has a 8x2 matrix.
It doesn't make much sense for them to be a cell array in that case. You could have an 8x2x4 matrix.
Fawad Farooq Ashraf
Fawad Farooq Ashraf 2021년 3월 14일
You're right, they could be a 3-dimensional matrix but I pass the cell element to another library function which uses it as elements of a cell array.

댓글을 달려면 로그인하십시오.

채택된 답변

Matt J
Matt J 2021년 3월 14일
편집: Matt J 2021년 3월 14일
[c{1:n}]=ndgrid(1:8);
c=reshape(cat(n+1,c{:}) [],n);
K=size(c,1);
Q=cell(n,1);
for i=1:n
Q{i}=reshape(M{i}( c(:,n+1-i),: ), 1,[],K);
end
P=num2cell(vertcat(Q{:}), [1,2]);
  댓글 수: 5
Fawad Farooq Ashraf
Fawad Farooq Ashraf 2021년 3월 14일
Sorry to bother you again @Matt J. But I think I'm still not getting the correct results. It'd be a great help if you could take a look at the test script I'm trying to run.
%%
M{1} = rand(8,2);
M{2} = rand(8,2);
%% Method 01
n = length(M);
[s,d] = cellfun(@size,M);
ncombs = prod(s);
P = cell(ncombs,1);
k = 0;
for i = 1:size(M{1},1)
for j = 1:size(M{2},1)
k = k+1;
P{k} = [M{1}(i,:);M{2}(j,:)];
end
end
%% Method 02
c = cell(1,n);
[c{1:n}] = ndgrid(1:size(M{1},1));
c = reshape(cat(n+1,c{:}), [],n);
K = size(c,1);
Q = cell(n,1);
for i=1:n
Q{i} = reshape(M{i}( c(:,n+1-i) , : ), 1,[],K);
end
P2 = num2cell(vertcat(Q{:}), [1,2]);
In this case, P{1} and P2{1} should match. But in P2, all the P2{i}(1,1) are equal to P2{i}(1,2) which doesn't quite seem right.
Fawad Farooq Ashraf
Fawad Farooq Ashraf 2021년 3월 14일
I found the error in my code. I had to take transpose there
Q{i} = reshape(M{i}( c(:,n+1-i) , : )', 1,[],K);
instead of
Q{i} = reshape(M{i}( c(:,n+1-i) , : ), 1,[],K);
Thanks a lot for the help.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by