2016-04-20 35 views
0

我需要的功能,用於尋找所有可能的子集的選擇,例如:功能查找所有可能的選擇

a=[1 3 4 7 8];b = nchoosek(a,3);b = 

1  3  4 
1  3  7 
1  3  8 
1  4  7 
1  4  8 
1  7  8 
3  4  7 
3  4  8 
3  7  8 
4  7  8 

我需要的所有可能的子集,如: 4 3 3 1,7 1,...

回答

3

如果輸出的順序很重要,則需要使用perms。每個排列將成爲結果中的新行。然後您可以抓住第一個k列並找到唯一的行。

a = [1 3 4]; 
k = 2; 

%// Generate all permutations of the index values corresponding to the input 
%// We use the index rather than the values of a to ensure that they are unique 
P = perms(1:numel(a)); 

%// Select the first k columns and find the unique rows 
P = unique(P(:,1:k), 'rows'); 

%// Now grab these elements from a 
b = a(P); 

%//  1  3 
%//  1  4 
%//  3  1 
%//  3  4 
%//  4  1 
%//  4  3 
+0

'perms'只能從5列表中挑選3個項目,但是? – Dan

+0

我的意思是n!/(n-k)!不是全部! – masih

+0

@Suever,感謝您的幫助 – masih