How to create a combination of matrix values in pairs?

8 views (last 30 days)
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?

Accepted Answer

Ameer Hamza
Ameer Hamza on 20 Jun 2020
Edited: Ameer Hamza on 20 Jun 2020
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)];

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!