'n' number of nested for loops

2 views (last 30 days)
Fawad Farooq Ashraf
Fawad Farooq Ashraf on 14 Mar 2021
Edited: Matt J on 14 Mar 2021
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 Comments
Matt J
Matt J on 14 Mar 2021
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 on 14 Mar 2021
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.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 14 Mar 2021
Edited: Matt J on 14 Mar 2021
[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 Comments
Fawad Farooq Ashraf
Fawad Farooq Ashraf on 14 Mar 2021
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 on 14 Mar 2021
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Special Functions in Help Center and File Exchange

Tags

Products


Release

R2020a

Community Treasure Hunt

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

Start Hunting!