在matlab中创建所有可能的行组合

时间:2014-04-14 15:20:52

标签: matlab combinations vectorization

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

因此行为R1,R2,最高为R9。

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

我目前正在使用for循环。

有没有更好的方法呢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在评论中,我不确定你是否总是想要第一行。此代码不会这样做,但您可以轻松地修改它。它仍然使用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

答案 2 :(得分:1)

函数nchoosek在给定向量时,将返回从该向量中选择k值的所有可能方法。你可以欺骗它,为你提供你想要的东西

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

这将包括从包含九个零的集合中选择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