# 'n' number of nested for loops

5 visualizzazioni (ultimi 30 giorni)
Fawad Farooq Ashraf il 14 Mar 2021
Modificato: Matt J il 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 CommentiMostra NessunoNascondi Nessuno
Matt J il 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 il 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.

Accedi per commentare.

### Risposta accettata

Matt J il 14 Mar 2021
Modificato: Matt J il 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 CommentiMostra 3 commenti meno recentiNascondi 3 commenti meno recenti
Fawad Farooq Ashraf il 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 il 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);
Q{i} = reshape(M{i}( c(:,n+1-i) , : ), 1,[],K);
Thanks a lot for the help.

Accedi per commentare.

### Categorie

Scopri di più su Matrix Indexing in Help Center e File Exchange

R2020a

### Community Treasure Hunt

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

Start Hunting!