Generate all possible combinations

50 次查看(过去 30 天)
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

采纳的回答

Bruno Luong
Bruno Luong 2018-11-29
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

更多回答(3 个)

madhan ravi
madhan ravi 2018-11-29
A = [1;2]
B = [3;4]
C = [5;6]
D = [7;8]
E=nchoosek([A(:); B(:) ;C(:); D(:)],4)

Michael Hartmann
Michael Hartmann 2021-11-29
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
Walter Roberson 2018-11-29
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.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

产品


版本

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by