1

Suppose we have 2 x N matrix in form of

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

There are 2^N combinations how the row can be rearranged. I'd like to find matrix B containing all the combinations.

%% 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|

This is very similar to the tables used for learning basics of Boolean algebra (ai=0,bi=1).

The question may be expanded to creating M^N x N matrix from M x N.

Crowley
  • 2,279
  • 6
  • 22
  • 36
  • Would this post be applicable to your cause? http://stackoverflow.com/questions/21895335/generate-a-matrix-containing-all-combinations-of-elements-taken-from-n-vectors – rayryeng Apr 05 '16 at 16:52
  • @rayryeng If I turn double matrix into array vector of double vectors, yes. But the Lous' answer here fits better. – Crowley Apr 05 '16 at 17:04
  • I understand. Good luck! – rayryeng Apr 05 '16 at 17:07
  • Here are some other approaches. http://stackoverflow.com/questions/4165859/generate-all-possible-combinations-of-the-elements-of-some-vectors-cartesian-pr Note that the sets in your case would be `{[a1 b1], [a2 b2], ...}` – beaker Apr 05 '16 at 21:10

1 Answers1

5

Try this:

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

It gives:

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

EDIT by @Crowley:

Expanding the answer to the last comment: dec2bin function is changed to dec2base with base of m (in following example we want to choose from three options for each column) and n columns.

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

This gives:

result =

    10    20
    10    50
    10    80
    40    20
    40    50
    40    80
    70    20
    70    50
    70    80
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147