MATLAB: Generate all possible combinations

generate possible combinations from matrixMATLAB

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

Best Answer

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