Generate all possible combinations
Show older comments
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
Accepted Answer
More Answers (3)
madhan ravi
on 29 Nov 2018
A = [1;2]
B = [3;4]
C = [5;6]
D = [7;8]
E=nchoosek([A(:); B(:) ;C(:); D(:)],4)
Michael Hartmann
on 29 Nov 2021
1 vote
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
Walter Roberson
on 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.
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!