生成包含元素的所有组合的矩阵从n个向量取 [英] Generate a matrix containing all combinations of elements taken from n vectors
问题描述
这个问题的一种形式经常弹出或其他(例如,见这里或的这里)。所以,我想我会美元的一般格式P $ psent它,并提供一个答案可能成为以供将来参考。
给定一个任意数量的
元素所采取的所有组合N
可能不同大小的矢量,产生一个N
-column矩阵,其行描述从这些向量(笛卡尔乘积)。
块引用>例如,
=向量{[1〜2],[3 6 9],[10 20]}
应该给
梳子= [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
是任意的,最好的办法是使用<一个href=\"http://www.mathworks.es/es/help/matlab/matlab_prog/comma-separated-lists.html?s_tid=doc_12b\">comma-separated列表(从单元阵列产生与N
细胞)作为输出。由此产生的N
然后矩阵连接成所需的N
-column矩阵:=向量{[1〜2],[3 6 9],[10 20]}; //%输入数据:向量单元阵列N = numel(矢量); //%向量的数量
梳=细胞(1,n)的; //%pre-定义生成逗号分隔的列表
[梳子{结束:-1:1}] = ndgrid(向量{结束:-1:1}); %//在这两个相反的顺序
%//逗号分隔的列表,需要以产生结果矩阵的行
//%字典序
梳=猫(n + 1个,梳子{:});沿着维数n + 1%// CONCAT的N,N-二暗淡阵列
梳子=重塑(梳子,[],N); //%重塑,以获得所需的矩阵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.
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) .For example,
vectors = { [1 2], [3 6 9], [10 20] }
should give
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 ]
解决方案The
ndgrid
function almost gives the answer, but has one caveat:n
output variables must be explicitly defined to call it. Sincen
is arbitrary, the best way is to use a comma-separated list (generated from a cell array withn
cells) to serve as output. The resultingn
matrices are then concatenated into the desiredn
-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屋!