生成包含元素的所有组合的矩阵从n个向量取 [英] Generate a matrix containing all combinations of elements taken from n vectors

查看:187
本文介绍了生成包含元素的所有组合的矩阵从n个向量取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题的一种形式经常弹出或其他(例如,见这里或的这里)。所以,我想我会美元的一般格式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 an n-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. Since n is arbitrary, the best way is to use a comma-separated list (generated from a cell array with ncells) 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆