MATLAB: How to create a combination of matrix values in pairs

combinationMATLABmatrix manipulation

I have a matrix lets say:
A=[1 4;2 5;3 6];
and i want to convert it into a matrix where each value in the first column is matched with each value in the second column:
B= 1 4
1 5
1 6
2 4
2 5
2 6
3 4
3 5
3 6
is there a vectorized way to do this?

Best Answer

If you have deep learning toolbox
A=[1 4;2 5;3 6];
B = combvec(A(:,2).', A(:,1).').';
Result
>> B
B =
4 1
5 1
6 1
4 2
5 2
6 2
4 3
5 3
6 3
Alternative without deep learning toolbox
A=[1 4;2 5;3 6];
[i1, i2] = ndgrid(1:size(A,1));
B = [A(i2(:),1) A(i1(:),2)];