Reputation: 11
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).
Upvotes: 1
Views: 91
Reputation: 36720
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.
Upvotes: 2
Reputation: 112769
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');
Upvotes: 0