简体   繁体   English

MATLAB:生成二进制矩阵的所有可能组合,每列中只有一个“ 1”

[英]MATLAB: Generate all possible combination of a binary matrix with only one '1' in each column

MATLAB : I want to find out how to generate all possible combination of a matrix (N by M) where: - elements are "1" and "0". MATLAB:我想找出如何生成矩阵的所有可能组合(N×M),其中:-元素为“ 1”和“ 0”。 - there should be only one "1" in each column. -每列中只能有一个“ 1”。 - no limitation for rows.so multiple "1" is allowed within each row. -行数没有限制。因此,每行中可以有多个“ 1”。

one possible state eg N=5 , M=6 一种可能的状态,例如N = 5,M = 6

1 0 1 0 0 0
0 1 0 0 0 1
0 0 0 0 0 0
0 0 0 1 1 0
0 0 0 0 0 0

furthermore I want to generate each possible combination matrix , then compute something (eg a utility function in my problem) like this : 此外,我想生成每个可能的组合矩阵,然后像这样计算某物(例如,我的问题中的效用函数):

generate one possible matrix C
.
  .
    for i=1:N
      for j=1:M
        do something on C(:,:)
      end
    end
  .
.

(in the manner of exhaustive search) (以详尽搜索的方式)

There will be lots . 会有很多 Usually when a question here involves: How do I generate all possible X , the real answer is: Don't do it, there are too many possible X . 通常,当一个问题涉及到: 我如何生成所有可能的X时 ,真正的答案是: 不要这样做,可能的X太多。 Look for a different approach to your problem. 寻找不同的方法来解决您的问题。

Nevertheless, you could use the number representation in the base of your number of rows: 不过,您可以在行数的基础上使用数字表示形式:

Approach using: dec2base 使用的方法: dec2base

Disclaimer: Due to limitations of dec2base this will only work for 2<=rows<=36 (Which is hopefully enough. Otherwise we would copy-edit the file dec2base.m and remove it's two last lines and the error check in line 24 to achieve arbitrary values of 2<=rows . This code I won't post for copyright reasons.). 免责声明:由于dec2base限制,此方法仅适用于2<=rows<=36 (希望足够。否则,我们将复制编辑dec2base.m文件并删除其最后两行,并在第24行进行错误检查取得2<=rows任意值。出于版权原因,我不会发布此代码。)。

rows = 5; 
cols = 6;
assert((2<=rows)&&(rows<=36),'The dec2base-approach will only work for 2<=rows<=36');
symbols = dec2base(0:rows-1, rows, 1);
for ii = 0:rows^cols-1
    % Compute ii in base rows.
    iibR = dec2base(ii, rows, cols);
    C = bsxfun(@eq, symbols, iibR);
    disp(C);
end

Generating the tuples without dec2base : 生成不带dec2base的元组:

We could also generate these tuples that represent our numbers using ndgrid . 我们还可以使用ndgrid生成这些表示我们数字的元组。

%%// Data
rows = 3;
cols = 4;
%%// Compute all k-tuples of numbers 1:n
n = rows;
k = cols;
Cs = cell(1,k);
[Cs{:}] = ndgrid(1:n);
tuples = reshape(cat(n+1, Cs{:}),n^k,[]);
%%// Compute matrices
for ii = 1:size(tuples,1);
    C = bsxfun(@eq, (1:rows).', tuples(ii,:));
    disp(C);
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM