1

I have a matrix which is 9x10000 size.

So rows are R1, R2, upto R9.

I want to generate all possible combination of the rows such as [R1;R2] [R1;R3].. [R1;R9] [R1;R2;R3]...[R1;R2;R4]... [R1;R2:R3;R4;..R8]

I am currently doing this using for loops.

Is there any better way of doing this.

dissw.geek9
  • 245
  • 1
  • 6
  • 11
  • Do you always want row 1? Your example suggests this. – Joe Serrano Apr 14 '14 at 15:33
  • 1
    Do you want to have all possible combinations in memory? That is a lot of redundant storage (since you have 512 possible combinations with anywhere from 10,000 to 90,000 elements in it). Probably better to be able to generate the nth combination on demand? – Floris Apr 14 '14 at 16:06
  • Take a look here: http://stackoverflow.com/questions/21895335/generate-a-matrix-containing-all-combinations-of-elements-taken-from-n-vectors – Luis Mendo Apr 14 '14 at 16:37

3 Answers3

1

Basically, counting up the binary from 1 to 2^9-i indicates which rows need to be selected:

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
Daniel
  • 36,610
  • 3
  • 36
  • 69
1

As in the comment, I'm not sure if you always want the first row. This code doesn't do that, but you can modify it for that easily enough. It still uses for loops, but relies on the "nchoosek" function for the row index generation.

%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
Joe Serrano
  • 424
  • 2
  • 7
1

The function nchoosek, when given a vector, will return all possible ways to choose k values from that vector. You can trick it into giving you what you want with

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

This will include all possible ways to select 9 values from the set that includes nine zeros, plus the indices of each of the rows. Now you have every possible combination (including "no row at all"). With this matrix generated just once, you can find any combination easily - without having to store them all in memory. You can now pick you combination:

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
Floris
  • 45,857
  • 6
  • 70
  • 122