# How to get the combinations of elements of two arrays?

206 views (last 30 days)
Hemming on 3 Dec 2018
Edited: Stephen23 on 27 Oct 2023
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 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

### Accepted Answer

Stephen23 on 3 Dec 2018
Edited: Stephen23 on 27 Oct 2023
A = [1,2,3];
B = [4,5];
[n,m] = ndgrid(B,A);
out = [m(:),n(:)]
out = 6×2
1 4 1 5 2 4 2 5 3 4 3 5
"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)
E = 6×2
1 4 1 5 2 4 2 5 3 4 3 5
This approach is from Dyuman Joshi's comment here:
##### 4 CommentsShow 2 older commentsHide 2 older comments
Stephen23 on 26 Oct 2023
@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 on 26 Oct 2023
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).

Sign in to comment.

### More Answers (3)

Mike Croucher on 4 Apr 2023
Edited: Mike Croucher on 4 Apr 2023
>> 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 CommentsShow -2 older commentsHide -2 older comments

Sign in to comment.

Jeff Miller on 3 Dec 2018
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 CommentShow -1 older commentsHide -1 older comments
Hemming on 11 Dec 2018
Edited: Hemming on 11 Dec 2018
Nice choice! And this code performs faster than the above one (MATLAB R2016a) although both adopt the similar method. Thanks a lot!

Sign in to comment.

ROHIT KHATRI on 26 Oct 2023
In MATLAB R2017b allcomb and combinations codes not working. So please tell me what can i do?
##### 1 CommentShow -1 older commentsHide -1 older comments
Stephen23 on 26 Oct 2023

Sign in to comment.

### Categories

Find more on Matrices and Arrays 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!