【问题标题】:Find the missing combinations找出缺失的组合
【发布时间】:2017-11-20 09:52:15
【问题描述】:

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

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

只需很小的更改即可获得所需的结果。

【问题讨论】:

  • 不,我想在不使用 nchosek 函数的情况下这样做!!
  • 为了保留您现有的方法,部分解决方案将不得不重置v,否则如果没有第 1 行,它永远不会有任何组合(可能还有另一个循环,它也控制i 的位置循环开始)
  • 那我们该怎么做呢?
  • 你怎么知道一个小小的改变就足够了?

标签: matlab combinations


【解决方案1】:

这个呢:

% 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

【讨论】:

    猜你喜欢
    • 2019-08-29
    • 1970-01-01
    • 2013-09-06
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多