3 回答
TA贡献1856条经验 获得超5个赞
ndgrid
n
n
n
n
n
vectors = { [1 2], [3 6 9], [10 20] }; %// input data: cell array of vectors
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
TA贡献1827条经验 获得超7个赞
combvec
:
vectors = {[1 2], [3 6 9], [10 20]};combs = combvec(vectors{:}).' % Use cells as arguments
combs = 1 3 10 2 3 10 1 6 10 2 6 10 1 9 10 2 9 10 1 3 20 2 3 20 1 6 20 2 6 20 1 9 20 2 9 20
sortrows
:
combs = sortrows(combvec(vectors{:}).')% Or equivalently as per @LuisMendo in the comments: % combs = fliplr(combvec(vectors{end:-1:1}).')
combs = 1 3 10 1 3 20 1 6 10 1 6 20 1 9 10 1 9 20 2 3 10 2 3 20 2 6 10 2 6 20 2 9 10 2 9 20
combvec
edit combvec
vectors = [1 2;3 6;10 20];vectors = num2cell(vectors,2);combs = sortrows(combvec(vectors{:}).')
TA贡献1820条经验 获得超9个赞
timeit
n
n/10
, n
n*10
n
240
ndgrid
combvec
combvec
基准代码
ndgrid
function combs = f1(vectors)n = numel(vectors); %// number of vectorscombs = 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 ordercombs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1combs = reshape(combs,[],n);
combvec
function combs = f2(vectors)combs = combvec(vectors{:}).';
timeit
nn = 20:20:240;t1 = [];t2 = [];for n = nn; %//vectors = {1:n, 1:n, 1:n}; vectors = {1:n/10, 1:n, 1:n*10}; t = timeit(@() f1(vectors)); t1 = [t1; t]; t = timeit(@() f2(vectors)); t2 = [t2; t];end
添加回答
举报