How to get the combinations of elements of two arrays?

조회 수: 270(최근 30일)
Hemming 2018년 12월 3일
편집: Hemming 2018년 12월 11일
Hi! I need to generate the combinations of elements of two arrays with different lengths. For example, if
A = [1,2,3]; B = [4,5];
I wish to get all combinations of elements from two arrays as
C = [1 4;1 5;2 4;2 5;3 4;3 5];
What comes to my mind is
[m,n] = meshgrid(A,B');
[C(:,1),C(:,2)] = deal(reshape(m,[],1),reshape(n,[],1));
Is there any more straight way to accomplish this?
And further, if I have three or more arrays to combine, what should I do?

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen 2018년 12월 3일
편집: Stephen 2018년 12월 3일
>> [m,n] = ndgrid(A,B);
>> Z = [m(:),n(:)]
Z =
1 4
2 4
3 4
1 5
2 5
3 5
"And further, if I have three or more arrays to combine, what should I do?"
Put then in a cell array:
C = {A,B,...};
D = C;
[D{:}] = ndgrid(C{:});
Z = cell2mat(cellfun(@(m)m(:),D,'uni',0))
and keep in mind that there is a limit to how much memory your computer has.
댓글 수: 1표시숨기기 없음
Hemming 2018년 12월 11일
Woooo! It works. Thanks a lot!

댓글을 달려면 로그인하십시오.

추가 답변(1개)

Jeff Miller 2018년 12월 3일
You might like allcomb on File Exchange:
For example:
>> A = [1,2,3]; B = [4,5];
>> C=allcomb(A,B)
C =
1 4
1 5
2 4
2 5
3 4
3 5
댓글 수: 1표시숨기기 없음
Hemming 2018년 12월 11일
Nice choice! And this code performs faster than the above one (MATLAB R2016a) although both adopt the similar method. Thanks a lot!

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

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

Start Hunting!

Translated by