Create matrix with indices of all unique combinations

14 Ansichten (letzte 30 Tage)
Alexander van Saase
Alexander van Saase am 18 Nov. 2020
Kommentiert: Ameer Hamza am 18 Nov. 2020
Say I have a vector ind = 1:4 and want to create a mx4 matrix of zeros and ones that represetns all unique combinations of these four indices, where m is the number of unique combinations, 16 in this case. So, the first few rows should look like like this:
A(1:7,:) = [0 0 0 0;
1 0 0 0;
0 1 0 0;
0 0 1 0;
0 0 0 1;
1 1 0 0;
1 0 1 0]
I noticed that the rows corresponds to the binary representation of the range 0:15. I tried using dec2bin(0:15) but this gives a gives a character vector. It can probably be converted to what I want, but I feel this is not the most efficient and elegant way of doing it.

Akzeptierte Antwort

Ameer Hamza
Ameer Hamza am 18 Nov. 2020
Bearbeitet: Ameer Hamza am 18 Nov. 2020
You can use dec2bin() like this
n = 4;
M = dec2bin(0:2^n-1)-'0';
Other then that, the easiest might be combvec() from deep learning toolbox
n = 4;
C = repmat({[0 1]}, 1, n);
M = combvec(C{:}).';
If you don't have the toolbox
n = 4;
C = repmat({[0 1]}, 1, n);
Cg = cell(size(C));
[Cg{:}] = ndgrid(C{:});
Cg = cellfun(@(x) {x(:)}, Cg);
M = cell2mat(Cg);
  2 Kommentare
Alexander van Saase
Alexander van Saase am 18 Nov. 2020
Your first solution is a bit of a hack, but works perfectly and with the least amount of code. Thanks!
Ameer Hamza
Ameer Hamza am 18 Nov. 2020
I am glad to be of help!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Data Type Conversion finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by