生成一个矩阵,其中包含取自 n 个向量的元素的所有组合 [英] Generate a matrix containing all combinations of elements taken from n vectors
问题描述
这个问题经常以一种或另一种形式出现(参见例如此处或此处).所以我想我会以一般形式呈现它,并提供一个答案以供将来参考.
This question pops up quite often in one form or another (see for example here or here). So I thought I'd present it in a general form, and provide an answer which might serve for future reference.
给定任意数量的 n
个可能不同大小的向量,生成一个 n
列矩阵,其行描述从这些向量中提取的元素的所有组合(笛卡尔积).
Given an arbitrary number
n
of vectors of possibly different sizes, generate ann
-column matrix whose rows describe all combinations of elements taken from those vectors (Cartesian product) .
例如
vectors = { [1 2], [3 6 9], [10 20] }
应该给
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 ]
推荐答案
ndgrid
函数几乎给出了答案,但有一个警告:必须明确定义 n
输出变量才能调用它.由于 n
是任意的,最好的方法是使用 逗号分隔列表(从带有 n
个单元格的单元格数组生成)作为输出.生成的 n
矩阵然后连接成所需的 n
列矩阵:
The ndgrid
function almost gives the answer, but has one caveat: n
output variables must be explicitly defined to call it. Since n
is arbitrary, the best way is to use a comma-separated list (generated from a cell array with n
cells) to serve as output. The resulting n
matrices are then concatenated into the desired n
-column matrix:
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
这篇关于生成一个矩阵,其中包含取自 n 个向量的元素的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!