找到缺少的组合

时间:2017-11-20 09:52:15

标签: matlab combinations

我正在使用这段代码来获取具有行的矩阵行的所有可能组合。代码如下:

sample = [1 1 ; 2 2; 3 3];
v = [];
for i = 1:size(sample,1)-1
    v = [v;(sample(i,:))];
    for j = 1:size(sample,1)
          if isequal(ismember(sample(j,:),v,'rows'),0) 
              display([v;sample(j,:)]);
          else
              j = j+1;
          end 
    end
end

此代码给出了以下输出:

ans =    
     1     1
     2     2


ans =    
     1     1
     3     3


ans =    
     1     1
     2     2
     3     3

但我需要这样的输出:

ans =    
     1     1


ans =    
     2     2


ans =    
     3     3


ans =    
     1     1
     2     2


ans =    
     1     1
     3     3


ans =    
     2     2
     3     3


ans =    
     1     1
     2     2
     3     3

只有一点点变化就足以获得理想的结果。

1 个答案:

答案 0 :(得分:0)

这个怎么样:

% getting the number of rows
n_row = size(sample,1);
% calculating all possible permutations of the rows
v = perms([1:n_row]);
disp('---')
% now we iterate over the permutations, as you want to have matrixes of 1,
% 2 and 3 rows
for i = 1: size(v,2)
    idx1 = v(:,1:i);
    % remove repeated answers
    idx1 = unique(idx1,'rows');
    % now we iterate over the answers and display
    for j = 1:size(idx1,1)
        idx2 = idx1(j,:);
        answer = sample(idx2,:);
        disp(answer)
        disp('---')
    end    
end