简体   繁体   中英

Matrix of all possible combinations of some numbers in MATLAB: how to be general on dimensions

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM