【问题标题】:Find all combinations of sets查找集合的所有组合
【发布时间】:2016-04-05 16:38:07
【问题描述】:

假设我们有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 矩阵。

【问题讨论】:

标签: matlab combinations


【解决方案1】:

试试这个:

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 函数更改为 dec2basebasem(在下面的示例中,我们希望从每列的三个选项中进行选择)和 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

【讨论】:

  • 这很整洁!
  • @dfri 谢谢! bsxfun FTW!
  • 这甚至适用于 A 作为单元格数组。非常整洁和健壮。
  • @Crowley 很好的概括!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-10
  • 1970-01-01
相关资源
最近更新 更多