How to get the combinations of elements of two arrays?
조회 수: 151 (최근 30일)
이전 댓글 표시
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?
댓글 수: 0
채택된 답변
Stephen23
2018년 12월 3일
편집: Stephen23
2023년 10월 27일
A = [1,2,3];
B = [4,5];
[n,m] = ndgrid(B,A);
out = [m(:),n(:)]
"And further, if I have three or more arrays to combine, what should I do?"
Put them all in a cell array and use two comma-separated lists:
C = {A,B};
[C{end:-1:1}] = ndgrid(C{end:-1:1});
EDIT: using CAT & RESHAPE is probably the most efficient approach:
n = numel(C);
E = reshape(cat(n,C{:}),[],n)
This approach is from Dyuman Joshi's comment here:
댓글 수: 4
Stephen23
2023년 10월 26일
@Dyuman Joshi: thank you, that is a very good approach! I copied it into my answer so that it does not get lost in the comments.
Dyuman Joshi
2023년 10월 26일
You are welcome!
Note that the usage of the indices in reverse order is to obtain the output in lexicographical manner (in the order of the values provided in the inputs).
추가 답변 (3개)
Jeff Miller
2018년 12월 3일
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
Mike Croucher
2023년 4월 4일
편집: Mike Croucher
2023년 4월 4일
As of MATLAB R2023a, the new combinations function can do this for you. Details at The new combinations function in MATLAB – for cartesian products and parameter sweeps » The MATLAB Blog - MATLAB & Simulink (mathworks.com)
>> A = [1,2,3];B=[4,5];
>> C = combinations(A,B)
C =
6×2 table
A B
_ _
1 4
1 5
2 4
2 5
3 4
3 5
The result is a table. When all data types are compatible (as is the case here) you can get the matrix like this
>> C.Variables
ans =
1 4
1 5
2 4
2 5
3 4
3 5
댓글 수: 0
ROHIT KHATRI
2023년 10월 26일
In MATLAB R2017b allcomb and combinations codes not working. So please tell me what can i do?
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!