Generate all possible combinations of a few numbers when the internal order doesn’t matter and the length varies?

2 ビュー (過去 30 日間)
Say I have three numbers: 1, 2 and 3 that I want to generate all possible combinations from, but the order in which they occur doesn’t matter. So for this example, using 1 2 3, this is what I want to generate:
1
1 2
1 2 3
2
2 3
1 3
3
The only combination generating function I know would be perms(1:3), but that would create:
3 2 1
3 1 2
2 3 1
2 1 3
1 2 3
1 3 2
In my situation the internal order in which the number occurs does not matter, so 1 2 means the same thing to me as 2 1 which should require fewer combinations.
Is there a command to generate sequences like this?
Thanks

採用された回答

Kirby Fears
Kirby Fears 2016 年 1 月 22 日
編集済み: Kirby Fears 2016 年 1 月 22 日
You're asking for the power set of your data. Careful not to use large arrays since the calculation will get out of hand rather quickly.
dataSet = [1 2 3];
n = numel(dataSet);
%idx = dec2bin(0:2^n-1,n)=='1'; % this is the whole power set
idx = dec2bin(1:2^n-2,n)=='1'; % this is nonempty proper subsets only
S = cell(size(idx,1),1);
for s = 1:size(idx,1),
S{s} = dataSet(idx(s,:));
end
Hope this helps.
  2 件のコメント
Peta
Peta 2016 年 1 月 22 日
Thank you that generated the numbers like I wanted!
Is there an easy way of converting S to a matrix where each number is separated by a column afterwards? cell2mat(S) complains because the cells are of varying length.
Kirby Fears
Kirby Fears 2016 年 1 月 22 日
編集済み: Kirby Fears 2016 年 1 月 22 日
You can't have blanks in a numeric array. You can have NaNs in the "blank" spaces though. I'd encourage you to work with the cells approach above. Just in case, here's an approach with NaNs in the empty positions:
dataSet = [1 2 3];
n = numel(dataSet);
%idx = dec2bin(0:2^n-1,n)=='1'; % this is the whole power set
idx = dec2bin(1:2^n-2,n)=='1'; % this is nonempty proper subsets only
S = NaN(size(idx));
for s = 1:size(idx,1),
S(s,idx(s,:)) = dataSet(idx(s,:));
end

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by