what function for computing all subsets given an array of consecutive number?

45 次查看(过去 30 天)
Hi I'm a little lost looking up the function call for the task: computing all subset of this array, which has 12 consecutive numbers So, like given we have
a = [1:12];
% need to get all 2^12 subsets [1, 2], [1, 2, 3]....
I'm trying but I don't think combntns() could work

回答(3 个)

John D'Errico
John D'Errico 2017-4-17
S = dec2bin(0:2^12-1) - '0';
The presence of a one in each row will indicate the elements included in the corresponding subset. There are 2^12 rows, this will be a list of all possible subsets.

Jan
Jan 2017-4-17
编辑:Jan 2017-4-17
a = 1:12;
R = cell(1, numel(a) + 1);
R{1} = [];
for k = 1:numel(a)
R{k + 1} = nchoosek(a, k);
end
Now R{k} contains the matrix with k-1 elements choosen from the input a. Or perhaps you want:
RR = cell(1, numel(a) + 1);
RR{1} = {[]};
for k = 1:numel(a)
RR{k + 1} = num2cell(nchoosek(a, k), 2);
end
R = cat(1, RR{:});

Charles Kluepfel
Charles Kluepfel 2024-8-9
编辑:Walter Roberson 2024-8-9
a = [1:12];
idxs = dec2bin(0:2^length(a)-1) - '0';
for i=1:length(idxs)
idx=idxs(i,:);
subset=a(find(idx));
disp(subset);
end
12
11
11 12
10
10 12
10 11
10 11 12
9
9 12
9 11
9 11 12
9 10
9 10 12
9 10 11
9 10 11 12
8
8 12
8 11
8 11 12
8 10
8 10 12
8 10 11
8 10 11 12
8 9
8 9 12
8 9 11
. . .
1 2 3 4 5 6 7 9 11 12
1 2 3 4 5 6 7 9 10
1 2 3 4 5 6 7 9 10 12
1 2 3 4 5 6 7 9 10 11
1 2 3 4 5 6 7 9 10 11 12
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 12
1 2 3 4 5 6 7 8 11
1 2 3 4 5 6 7 8 11 12
1 2 3 4 5 6 7 8 10
1 2 3 4 5 6 7 8 10 12
1 2 3 4 5 6 7 8 10 11
1 2 3 4 5 6 7 8 10 11 12
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 12
1 2 3 4 5 6 7 8 9 11
1 2 3 4 5 6 7 8 9 11 12
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 12
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12
  1 个评论
Walter Roberson
Walter Roberson 2024-8-9
You can do slightly better,
a = [1:12];
idxs = logical(dec2bin(0:2^length(a)-1) - '0');
for i=1:length(idxs)
subset = a(idxs(i,:));
disp(subset);
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by