3 回答
TA貢獻1856條經驗 獲得超5個贊
ndgridnnnnn
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條經驗 獲得超8個贊
combvec:
vectors = {[1 2], [3 6 9], [10 20]};combs = combvec(vectors{:}).' % Use cells as argumentscombs = 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
combvecedit combvec
vectors = [1 2;3 6;10 20];vectors = num2cell(vectors,2);combs = sortrows(combvec(vectors{:}).')TA貢獻1820條經驗 獲得超9個贊
timeit
nn/10, nn*10n240
ndgridcombveccombvec
基準代碼
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添加回答
舉報
