Reputation: 2331
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
.
Upvotes: 1
Views: 69
Reputation: 112669
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
Upvotes: 5