'n' number of nested for loops

4 次查看(过去 30 天)
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
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
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
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