2017-12-07 19 views
2

집합의 가능한 모든 조합을 찾으려고하지만 요소의 순서 또한 내 문제에 중요합니다.Matlab의 모든 가능한 조합 조합

예를 들어 집합 set={A, B, C}의 경우, 가능한 하위 집합은 subsets={A},{B},{C},{A,B},{A,C},{B,A},{B,C},{C,A},{C,B},{A,B,C},{A,C,B},{B,A,C},{B,C,A},{C,A,B},{C,B,A}입니다.

찾을 수있는 Matlab 함수가 있습니까?

미리 감사드립니다. 이 결과는 가변 길이의 단일 벡터에 동일한 크기의 컬럼으로 구성, 오히려 삽입하지 않으려면

답변

3

나는 모든 for을 차마 볼 수 없었다 그래서 여기 Tommaso's answer에 루프없는 루프가 하나 :이 마소의 두 번째 졸처럼 각 요소에서 하나의 순열과 셀 배열을 반환

a = {'A' 'B' 'C'}; 

% Build an array of binary vectors which we will use to select subsets of 
% the array to be permuted 
nGroups = 2^numel(a) - 1; 
selector = dec2bin(1:nGroups) == '1'; % hack to convert numbers to binary vectors 
selectVectors = arrayfun(@(x) selector(x,:), 1:size(selector, 1), 'UniformOutput', false); 

% Get the permutations of each subset of the array 
permsCell = cellfun(@(s) perms(a(s)), selectVectors, 'UniformOutput', false); 

% Rearrange the permutations into a one-dimensional cell array with one 
% permutation in each element 
rowsAsCells = @(ca) arrayfun(@(x) ca(x,:), 1:size(ca,1), 'UniformOutput', false); 
permsAsRows = cellfun(rowsAsCells, permsCell, 'UniformOutput', false); 
result = cat(2, permsAsRows{:}); 

ution. 이 버전이 바람직하다 여부

는 다양한`* fun` 기능 * 것을 맛 ;-)

+0

주의의 문제입니다 * 내부 루프와 동등한 명시 적 루프에 비해 일반적으로 더 적은 확대됨. 그래도 트위터를 코딩하는 것이 더 좋은 경우가 있습니다. – excaza

+0

하하. 필자는'cellfun'과'arrayfun'이 때로는 등가 루프 구현보다 읽기 쉽다고 생각합니다. (성가신'UniformOutput' 비즈니스가 아니라면 더 많이 읽을 것입니다.) 나는 이것이 반드시 그러한 경우 중 하나라고 주장하지 않습니다. – nekomatic

1
a = {'A' 'B' 'C'}; 
a_len = numel(a); 

res_len = 0; 

for i = 1:a_len 
    res_len = res_len + (factorial(a_len)/factorial(a_len - i)); 
end 

res = cell(res_len,a_len); 
res_off = 1; 

for i = 1:a_len 
    bin = nchoosek(a,i); 

    for j = 1:size(bin,1) 
     bin_j = bin(j,:); 

     per = perms(bin_j); 
     per_hei = size(per,1); 

     res_ran = res_off + per_hei - 1; 
     res(res_off:res_ran,:) = [per repmat({''},size(per,1),a_len - i)]; 
     res_off = res_off + per_hei; 
    end 
end 

또는 :

a = {'A' 'B' 'C'}; 
a_len = numel(a); 

res_len = 0; 

for i = 1:a_len 
    res_len = res_len + (factorial(a_len)/factorial(a_len - i)); 
end 

res = cell(res_len,1); 
res_off = 1; 

for i = 1:numel(a) 
    bin = nchoosek(a,i); 

    for j = 1:size(bin,1) 
     bin_j = bin(j,:); 
     per = perms(bin_j); 

     for y = 1:size(per,1) 
      res{res_off,1} = {per{y,:}}; 
      res_off = res_off + 1; 
     end 
    end 
end