简体   繁体   中英

How do I find all permutations from a matrix with one value per column in Matlab?

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).

看一下这个函数allcombo([25:28],[53:56 59:60],52,[25:28],[37:38])应该是您想要的。

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM