MATLAB: How to get the combinations of elements of two arrays

arraycombination

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?

Best Answer

>> [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.