Generate all possible combinations
46 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Billie Jaya
le 29 Nov 2018
Réponse apportée : Michael Hartmann
le 29 Nov 2021
Hi Guys,
I want to combine 4 matrix & get all the possible combinations
the example is
I have matrix A,B,C,D
A = [1;2]
B = [3;4]
C = [5;6]
D = [7;8]
I want to generate all matrix E Combinations
E = [1 3 5 7;1 3 5 8; 1 3 6 7; 1 3 6 8; 1 4 5 7;1 4 5 8; 1 4 6 7; 1 4 6 8;2 3 5 7;2 3 5 8; 2 3 6 7; 2 3 6 8; 2 4 5 7;2 4 5 8; 2 4 6 7; 2 4 6 8 ]
And is there any matlab function to generate it ?
thanks
0 commentaires
Réponse acceptée
Bruno Luong
le 29 Nov 2018
A = [1;2]
B = [3;4]
C = [5;6]
D = [7;8]
L = {A,B,C,D};
n = length(L);
[L{:}] = ndgrid(L{end:-1:1});
L = cat(n+1,L{:});
L = fliplr(reshape(L,[],n))
Which gives
L =
1 3 5 7
1 3 5 8
1 3 6 7
1 3 6 8
1 4 5 7
1 4 5 8
1 4 6 7
1 4 6 8
2 3 5 7
2 3 5 8
2 3 6 7
2 3 6 8
2 4 5 7
2 4 5 8
2 4 6 7
2 4 6 8
1 commentaire
Plus de réponses (3)
madhan ravi
le 29 Nov 2018
A = [1;2]
B = [3;4]
C = [5;6]
D = [7;8]
E=nchoosek([A(:); B(:) ;C(:); D(:)],4)
0 commentaires
Michael Hartmann
le 29 Nov 2021
Option: for one single vector
a=1:4
fliplr(combvec(a, a, a)')'
could also be
a=1:4
b=1:3
c=1:2
fliplr(combvec(a, b, c)')'
ans =
1 1 1
1 1 2
1 1 3
1 1 4
1 2 1
1 2 2
1 2 3
1 2 4
1 3 1
1 3 2
1 3 3
1 3 4
2 1 1
2 1 2
2 1 3
2 1 4
2 2 1
2 2 2
2 2 3
2 2 4
2 3 1
2 3 2
2 3 3
2 3 4
0 commentaires
Walter Roberson
le 29 Nov 2018
The meshgrid() solution that Bruno suggested to your earlier question can be extended to 3 arrays. For more arrays than that you need to switch to ndgrid() . ndgrid() and meshgrid() are very similar, but the first two dimensions are exchanged.
>> meshgrid(1:3,1:4)
ans =
1 2 3
1 2 3
1 2 3
1 2 3
>> ndgrid(1:3,1:4)
ans =
1 1 1 1
2 2 2 2
3 3 3 3
With ndgrid, the length of the first parameter becomes the size of the first dimension, the length of the second paramter becomes the size of the second dimension, and so on.
0 commentaires
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!