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

41 views (last 30 days)
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

Answers (3)

John D'Errico
John D'Errico on 17 Apr 2017
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 on 17 Apr 2017
Edited: Jan on 17 Apr 2017
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 on 9 Aug 2024
Edited: Walter Roberson on 9 Aug 2024
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 Comment
Walter Roberson
Walter Roberson on 9 Aug 2024
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

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!