在Matlab中生成矩阵的所有可能组合 [英] Generate All Possible combinations of a Matrix in Matlab

查看:571
本文介绍了在Matlab中生成矩阵的所有可能组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在知道该矩阵的元素只能为0或1的情况下,如何为N * M矩阵生成所有可能的值?

How can I generate ALL possible values for an N*M matrix, knowing that elements of this matrix can only be either be 0 or 1?

例如,如果我想要一个2 * 2矩阵,我们得到16种矩阵,它们具有不同的可能组合:[0 0; 0 0],[1 1; 1 1],[1 0; 0 1],[1 1; 0 0],[0 0; 1 1] ...等

For example if I want a 2*2 matrix, we get 16 matrices with the different possible combinations: [0 0;0 0], [1 1;1 1], [1 0;0 1],[1 1; 0 0],[0 0;1 1]...etc

推荐答案

使用 这将在行中生成所有可能的组合.因此,要选择任何组合,您需要索引到combs.因此,第一个组合[0,0,0,0]combs(1,:)处可用,最后一个[1,1,1,1]comb(end,:)处.

This generates all the possible combinations in rows. So, to select any combination, you need to index into combs. Thus, the first combination [0,0,0,0] would be available at combs(1,:) and the last one [1,1,1,1] would be at comb(end,:).

如果可能的值来自不同的集合,例如0,1,2,3,请进行此编辑-

If your possible values are from a different set, like 0,1,2,3 instead, make this edit -

combs = dec2base(0:power(4,N*M)-1,4) - '0'


如果要获得与输入矩阵大小相同的组合,请使用此-


If you would to get the combinations that would be sized identically to the input matrix, use this -

combs_matshaped = reshape(permute(combs,[3 2 1]),N,M,[])

这将创建一个3D数组,其中包含与组合数量一样多的2D切片,并且矩阵的每个组合都具有三维索引"功能.例如,如果要获得第一个组合,请使用combs_matshaped(:,:,1),对于最后一个组合,请使用combs_matshaped(:,:,end).

This creates a 3D array of as many 2D slices as there are combinations and each combination for the matrix is "index-able" with the third dimension index. For example, if you intend to get the first combination, use combs_matshaped(:,:,1) and for the last one, use combs_matshaped(:,:,end).

这篇关于在Matlab中生成矩阵的所有可能组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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