1

I'm fairly new to Matlab (and programming in general) and I can't figure out how to do this. Perhaps it is quite simple, but I could really use some help. I've got this matrix:

25    53    52    25    37
26    54     0    26    38
27    55     0    27     0
28    56     0    28     0
 0    59     0     0     0
 0    60     0     0     0

I would like to compute all different combinations, in terms of rows with one value from each column, like, 25,53,52,25,37 and 25,54,52,26,38 and 25,54,52,27,0 etc. Besides, I want to discard the combinations containing 0 (like 25,53,0,25,37).

Cœur
  • 37,241
  • 25
  • 195
  • 267
kona
  • 11
  • 1

2 Answers2

2

Take a look at this function, allcombo([25:28],[53:56 59:60],52,[25:28],[37:38]) should be what you are looking for.

Divakar
  • 218,885
  • 19
  • 262
  • 358
Daniel
  • 36,610
  • 3
  • 36
  • 69
  • This would certainly what I want! But, unfortunately Matlab does not seem to recognize it? >> allcombo([25:28],[53:60],52,[25:28],[37:38]) Undefined function 'allcombo' for input arguments of type 'double'. – kona Apr 05 '14 at 18:55
  • I linked a function of the matlab file exchange. It's a portal where matlab users upload functions for other matlab users, you have to download it and put it to your search path. – Daniel Apr 05 '14 at 18:56
  • 1
    +1 Kool tool that one! Edited the code for some correction, hope that was okay. – Divakar Apr 05 '14 at 22:50
0

Adapted from this answer:

M = [ 25    53    52    25    37
       26    54     0    26    38
       27    55     0    27     0
       28    56     0    28     0
        0    59     0     0     0
        0    60     0     0     0 ]; %// data matrix

[m n] = size(M);
C = mat2cell(M, m, ones(1,n)); %// convert to cell array of column vectors
combs = cell(1,n); %// pre-define to generate comma-separated list
[combs{end:-1:1}] = ndgrid(C{end:-1:1}); %// the reverse order in these two
%// comma-separated lists is needed to produce the rows of the result matrix in
%// lexicographical order 
combs = cat(n+1, combs{:}); %// concat the n n-dim arrays along dimension n+1
combs = reshape(combs,[],n); %// result: each row gives a combination

This gives, in your example:

>> combs(1:5,:)
ans =
    25    53    52    25    37
    25    53    52    25    38
    25    53    52    25     0
    25    53    52    25     0
    . . .

If any column has repeated entries, the result will have repeated rows. To keep only unique rows (note this changes the order of the rows):

combs = unique(combs,'rows');
Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147