Create matrix with indices of all unique combinations

11 views (last 30 days)
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.

Accepted Answer

Ameer Hamza
Ameer Hamza on 18 Nov 2020
Edited: Ameer Hamza on 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 Comments
Alexander van Saase
Alexander van Saase on 18 Nov 2020
Your first solution is a bit of a hack, but works perfectly and with the least amount of code. Thanks!

Sign in to comment.

More Answers (0)

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!