How to generate all 2^n combinations of n choices from a 2-vector?
9 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
採用された回答
John D'Errico
2025 年 5 月 31 日
編集済み: John D'Errico
2025 年 5 月 31 日
Simple enough. Don't use combinations.
n = 3;
t = dec2bin(0:2^n - 1) - '0'
Easy enough to make that into a table if you so desire.
Sigh. Do you INSIST on using combinations? This will suffice.
v = repmat({[0 1]},1,n);
t2 = combinations(v{:})
I can think of at least a couple other ways if pushed, but they shoiuld work.
3 件のコメント
Steven Lord
2025 年 6 月 2 日
And of course, if you want a matrix from combinations (assuming all the table variables can be concatenated together) you can do that by indexing into the output from the function call.
n = 3;
t = dec2bin(0:2^n - 1) - '0';
v = repmat({[0 1]},1,n);
t2 = combinations(v{:}).Variables
doTheyMatch = isequal(t, t2)
You need to be careful, though, if you have mixed types.
t3 = combinations([0 1], ["apple", "banana"])
t4 = t3.Variables % Note that this is a string array, using "0" and "1" not 0 and 1
Matt J
2025 年 6 月 2 日
編集済み: Matt J
2025 年 6 月 2 日
The spped performance as a function of n is interesting. combinations() starts to overtake ndgrid() only for n>=20 or so. I would have expected combinations() to benefit from avoiding a cat() operation.
Timing(15)
Timing(20)
function Timing(n)
timeit(@() methodDEC2BIN(n))
timeit(@() methodCOMBINATIONS(n))
timeit(@() methodNDGRID(n))
end
function methodDEC2BIN(n)
t = dec2bin(0:2^n - 1) - '0';
end
function methodCOMBINATIONS(n)
v = repmat({[0 1]},1,n);
t = combinations(v{:});
end
function methodNDGRID(n)
[t{n:-1:1}]=ndgrid([0,1]);
t=reshape( cat(n+1, t{:}) , [],n);
end
参考
カテゴリ
Help Center および File Exchange で Matrix Indexing についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!