Generate all possible combinations

조회 수: 45 (최근 30일)
Billie Jaya
Billie Jaya 2018년 11월 29일
답변: Michael Hartmann 2021년 11월 29일
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