【问题标题】:Creating all possible combination of rows in matlab在matlab中创建所有可能的行组合
【发布时间】:2014-04-14 15:20:52
【问题描述】:

我有一个 9x10000 大小的矩阵。

所以行是 R1、R2,直到 R9。

我想生成所有可能的行组合,例如 [R1;R2] [R1;R3].. [R1;R9] [R1;R2;R3]...[R1;R2;R4]...[R1;R2:R3;R4;..R8]

我目前正在使用 for 循环执行此操作。

有没有更好的方法。

【问题讨论】:

  • 你总是想要第 1 行吗?你的例子表明了这一点。
  • 你想在内存中拥有所有可能的组合吗?这是大量的冗余存储(因为您有 512 种可能的组合,其中包含 10,000 到 90,000 个元素)。能够按需生成第 n 个组合可能更好?

标签: matlab combinations vectorization


【解决方案1】:

基本上,将二进制从 1 计数到 2^9-i 表示需要选择哪些行:

M=... your matrix
S=dec2bin(1:2^size(M,1)-1)=='1';
allSubsets=cell(size(S,1),1);
for ix=1:size(S,1)
    allSubsets{ix}=M(find(S(ix,:)),:);
end

【讨论】:

    【解决方案2】:

    正如评论中所说,我不确定您是否总是想要第一行。这段代码没有这样做,但你可以很容易地修改它。它仍然使用 for 循环,但依赖于“nchoosek”函数来生成行索引。

    %generate data matrix
    nMax=9; %number of rows
    M=rand(nMax,1e4); %the data
    
    %cell array of matrices with row combinations
    select=cell(2^nMax-nMax-1,1); %ignore singletons, empty set
    
    %for loop to generate the row selections
    idx=0;
    for i=2:nMax 
        %I is the matrix of row selections
        I=nchoosek(1:nMax,i); 
    
        %step through the row selections and form the new matrices
        for j=1:size(I,1) 
            idx=idx+1;   %idx tracks number of entries
            select{idx}=M(I(j,:),:); %select{idx} is the new matrix with selected rows
            %per Floris' comment above you could do
            %select{idx}=I(j,:); %save the selection for later
        end
    end
    

    【讨论】:

      【解决方案3】:

      函数nchoosek,当给定一个向量时,将返回从该向量中选择k 值的所有可能方式。你可以欺骗它给你想要的东西

      allCombis = unique(nchoosek([zeros(1,9) 1:9], 9), 'rows');
      

      这将包括从包含 9 个零的集合中选择 9 个值的所有可能方法,以及每行的索引。现在您有了所有可能的组合(包括“根本没有行”)。只需生成一次此矩阵,您就可以轻松找到任何组合 - 无需将它们全部存储在内存中。您现在可以选择组合:

      thisNumber = 49; % pick any combination
      rows = allCombis(thisNumber, :);
      rows(rows==0)=[]; % get rid of the zeros
      thisCombination = myMatrix(rows, :); % pick just the rows corresponding to this combination
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多