Create matrix with indices of all unique combinations
11 views (last 30 days)
Show older comments
Alexander van Saase
on 18 Nov 2020
Commented: Ameer Hamza
on 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.
0 Comments
Accepted Answer
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
More Answers (0)
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!