在Matlab中,我试图创建一个3^(n-1(乘n的矩阵,每行包含三项树的场景。总的来说,所有的行一起包含树中可以遵循的所有可能的路径。在树上的每一点上,路径要么向上,要么保持不变,要么向下。我想在矩阵中分别用1、0或-1来表示。n=3的一个例子是:
[0,-1,-1;
0,-1,0;
0,-1,1;
0,0,-1;
0,0,0;
0,0,1;
0,1,-1;
0,1,0;
0,1,1]
我想把它推广到n个步骤。
您的问题在这里基本上得到了回答,由Luis Mendo撰写。只需要小的调整。
你想要的是的所有组合
vectors = { [0], [-1 0 1], [-1 0 1] }; %matching your example
或者更普遍地说,对于任意:
vectors = [0,repmat({[-1 0 1]},1,n-1)]; %start with 0, then repeat [-1,0,1] n times
然后你可以继续链接答案,在这里引用:
n = numel(vectors); %// number of vectors combs = cell(1,n); %// pre-define to generate comma-separated list [combs{end:-1:1}] = ndgrid(vectors{end:-1:1}); %// the reverse order in these two %// comma-separated lists is needed to produce the rows of the result matrix in %// lexicographical order combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1 combs = reshape(combs,[],n); %// reshape to obtain desired matrix