Finding all possible combinations of a matrix

Hello Everyone,
I have the following matrix:
mat=[0 0 0 0;1 1 1 1;2 2 2 2;3 3 3 3]
and i want to create a new matrix from it that would have all possible combinations: [ 0 0 0 0; 0 0 0 1; 0 0 0 2; 0 0 0 3; 0 0 1 0; 0 0 2 0; . . . ;3 3 3 3]
How can I do that?
Thanks a lot in advance
Best Regards, Sameh

 採用された回答

sameh eldessoki
sameh eldessoki 2015 年 11 月 17 日

0 投票

Hello All,
for "U=4" --> the inputs of the input matrix (0,1,2,3) and "depth=4" --> (number of columns of the output matrix)
I have found a simple answer, which is also generic for other values of "U" and "depth":
combs = dec2base(0:power(U,depth)-1,U) - '0';
Thank you all for your replies and I hope that my answer or yours would be of help to others as well.
Best Regards,
Sameh

1 件のコメント

Guillaume
Guillaume 2015 年 11 月 17 日
This is basically the first part of my answer. As stated in my answer, this only works for U < 10.

サインインしてコメントする。

その他の回答 (2 件)

Thorsten
Thorsten 2015 年 11 月 17 日
編集済み: Thorsten 2015 年 11 月 17 日

0 投票

val = 0:3;
X = [];
for i = val, for j= val, for k = val, for l = val, X = [X; [i,j,k,l]]; end, end, end, end
or
val = 0:3;
[w x y z] = ndgrid(val);
X = [z(:) y(:) x(:) w(:)];

2 件のコメント

Guillaume
Guillaume 2015 年 11 月 17 日
This is hardly generic to any input mat of an arbitrary size
sameh eldessoki
sameh eldessoki 2015 年 11 月 17 日
@Thorsten the second part of your answer is very useful, but won't have control over the number of columns of the output matrix.

サインインしてコメントする。

Guillaume
Guillaume 2015 年 11 月 17 日
編集済み: Guillaume 2015 年 11 月 17 日

0 投票

This will work as long as mat has less than 10 rows:
assert(size(mat, 1) < 10, 'mat has too many rows')
rowidx = dec2base(0 : size(mat, 1).^size(mat, 2)-1, size(mat, 1)) - '0' + 1;
colidx = repmat(1:size(mat, 2), size(mat, 1).^size(mat, 2), 1);
result = mat(sub2ind(size(mat), rowidx, colidx))
There's no limit on the number of columns (other than memory / computation time)
edit:
if more than 10 rows, then you can use ndgrid as per Thorsten's answer to generate the rowidx:
rowvals = cell(1, size(mat, 2)); %to receive output of ndgrid
[rowvals{:}] = ndgrid(1:size(mat, 1));
rowidx = reshape(cat(size(mat, 2)+1, rowvals{:}), size(mat, 1).^size(mat, 2), size(mat, 2));
%continue as before

1 件のコメント

sameh eldessoki
sameh eldessoki 2015 年 11 月 17 日
@Guillaume I guess your edit does what i want with freedom for the choice of the number of rows and columns. However, it might be a bit complicated. Anyhow, thanks a lot for your effort :)

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Identification についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by