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

15 vues (au cours des 30 derniers jours)
Trung Ngo
Trung Ngo le 17 Avr 2017
Commenté : Walter Roberson le 9 Août 2024
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 commentaire
Bhanu Pratap Yadav
Bhanu Pratap Yadav le 29 Nov 2023
Déplacé(e) : Walter Roberson le 9 Août 2024
can you give a MATLAB code so that I can generate all subsets of given number of elements

Connectez-vous pour commenter.

Réponses (3)

John D'Errico
John D'Errico le 17 Avr 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 le 17 Avr 2017
Modifié(e) : Jan le 17 Avr 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 le 9 Août 2024
Modifié(e) : Walter Roberson le 9 Août 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 commentaire
Walter Roberson
Walter Roberson le 9 Août 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Resizing and Reshaping Matrices dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by