MATLAB: Create matrix with indices of all unique combinations

indices

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.

Best Answer

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);