查找集合的所有组合

Find all combinations of sets

假设我们有 2 x N 形式的矩阵

A=| a1 a2 ... aN |
  | b1 b2 ... bN |

有 2^N 种组合可以重新排列行。我想找到包含所有组合的矩阵 B

%% N=2
B=|a1 a2|
  |a1 b2|
  |b1 a2|
  |b1 b2|
%% N=3
B=|a1 a2 a3|
  |a1 a2 b3|
  |a1 b2 a3|
  |a1 b2 b3|
  |b1 a2 a3|
  |b1 a2 b3|
  |b1 b2 a3|
  |b1 b2 b3|

这与用于学习布尔代数基础知识 (ai=0,bi=1) 的表格非常相似。

问题可以扩展为从 M x N 创建 M^N x N 矩阵。

试试这个:

A = [10 20 30; 40 50 60]; %// data matrix
[m, n] = size(A); %// m: number of rows; n: number of cols
t = dec2bin(0:2^n-1)-'0'; %// generate all possible patterns
t = bsxfun(@plus, t, 1:m:n*m-1); %// convert to linear index
result = A(t); %// index into A to get result

它给出:

result =
    10    20    30
    10    20    60
    10    50    30
    10    50    60
    40    20    30
    40    20    60
    40    50    30
    40    50    60

编辑 @Crowley:

扩展对最后一条评论的回答: dec2bin 函数更改为 dec2basebase of m(在下面的示例中,我们希望为每一列选择三个选项)和 n 列。

A = [10 20;...
     40 50;...
     70 80]; %// data matrix
[m, n] = size(A); %// m: number of rows; n: number of cols
t = dec2base(0:m^n-1,m,n)-'0'; %// generate all possible patterns
t = bsxfun(@plus, t, 1:m:n*m-1); %// convert to linear index
result = A(t) %// index into A to get result

这给出:

result =

    10    20
    10    50
    10    80
    40    20
    40    50
    40    80
    70    20
    70    50
    70    80