what function for computing all subsets given an array of consecutive number?
35 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
1 Kommentar
Bhanu Pratap Yadav
am 29 Nov. 2023
Verschoben: Walter Roberson
am 9 Aug. 2024
can you give a MATLAB code so that I can generate all subsets of given number of elements
Antworten (3)
John D'Errico
am 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.
0 Kommentare
Jan
am 17 Apr. 2017
Bearbeitet: Jan
am 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{:});
0 Kommentare
Charles Kluepfel
am 9 Aug. 2024
Bearbeitet: Walter Roberson
am 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 Kommentar
Walter Roberson
am 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
Siehe auch
Kategorien
Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!