0

Consider a MATLAB cell U of size L x 1, where each sub-cell is a G x K matrix reporting some numbers. I want to construct a cell T of size G x 1, where each sub-cell g is a K^L x L matrix reporting all the possible L-tuples from U{1}(g,:), U{2}(g,:), ..., U{L}(g,:). For example, consider

L=3;
G=5;
K=4;
%U=cell(L,1);
U{1}=randn(5,4);
U{2}=randn(5,4);
U{3}=randn(5,4);
T=cell(G,1);
for g=1:G
    U1=U{1}(g,:);
    U2=U{2}(g,:);
    U3=U{3}(g,:);
    [ca, cb, cc] = ndgrid(U1, U2, U3);
    T{g} = [ca(:), cb(:), cc(:)]; 
end

How can I generalise this code to any L?

I think I could use and modify the answer to this question but I'm struggling to set the input variables.

TEX
  • 2,249
  • 20
  • 43
  • Thanks. I have added what I'm looking for. I though that this question was enough different from the other to be worth it a separate answer. – TEX Jun 26 '20 at 12:00
  • I presume you meant `U{1}, U{2}, U{3}` in the loop? Anyway, you can treat `U1, U2, U3` also as a matrix, where `ndgrid` will take it per column (I think, output size is at least correct), so you could simply concatenate all relevant columns from all cells into a matrix. – Adriaan Jun 26 '20 at 12:04

1 Answers1

2

I slightly adapted the solution of the other topic:

L=3;
G=5;
K=4;
U=cell(L,1);
U = cellfun(@(x) {randn(G,K)}, U);
T=cell(G,1);
for g=1:G
    Cin = cellfun(@(x) {x(g,:)}, U);
    Cout = cell(L,1);
    [Cout{:}] = ndgrid(Cin{:});
    Cout = cellfun(@(x) {x(:)}, Cout);
    T{g} = [Cout{:}];
end

Does that do what you want ?

bousof
  • 1,241
  • 11
  • 13