How to generate all 2^n combinations of n choices from a 2-vector?
Show older comments
If I want all combinations of 3 choices of 0 or 1, I do this:
t = combinations([0 1],[0 1],[0 1]);
If I want all combinations of 4 choices, I have to do this:
t = combinations([0 1],[0 1],[0 1],[0,1])
If I want all combinations of 5 choices, I have to do this:
t = combinations([0 1],[0 1],[0 1],[0,1],[0 1])
...and so on. Is there any way to generate all combination of a variable number of choices?
Accepted Answer
More Answers (1)
n=3;
clear t
[t{n:-1:1}]=ndgrid([0,1]);
t=reshape( cat(n+1, t{:}) , [],n)
Categories
Find more on Matrix Indexing 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!