生成某些向量元素的所有可能组合(笛卡尔积) [英] Generate all possible combinations of the elements of some vectors (Cartesian product)

查看:28
本文介绍了生成某些向量元素的所有可能组合(笛卡尔积)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成给定数量向量的元素的所有可能组合.

I would like to generate all the possible combinations of the elements of a given number of vectors.

例如,对于[1 2][1 2][4 5]我要生成的元素:

For example, for [1 2], [1 2] and [4 5] I want to generate the elements:

<代码>[1 1 4;1 1 5;1 2 4;1 2 5;2 1 4;2 1 5;2 2 4;2 2 5]

问题是我不知道需要计算组合的向量数量.在这种情况下可能有 3 个,也可能有 10 个,我需要一个概括.你能在 MATLAB 中帮我解决这个问题吗?是否已经有一个预定义的函数可以完成这个任务?

The problem is that I don't know the number of vectors for which I need to calculate the combinations. There might be 3 as in this case, or there may be 10, and I need a generalization. Can you please help me to this in MATLAB? Is there already a predefined function that can do this task?

推荐答案

在 FileExchange 中尝试 ALLCOMB 函数.

Try ALLCOMB function at FileExchange.

如果将向量存储在元胞数组中,则可以像这样运行:

If you store you vectors in a cell array, you can run it like this:

a = {[1 2], [1 2], [4 5]};
allcomb(a{:})
ans =

     1     1     4
     1     1     5
     1     2     4
     1     2     5
     2     1     4
     2     1     5
     2     2     4
     2     2     5

这篇关于生成某些向量元素的所有可能组合(笛卡尔积)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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