How can I extract unique pairs of matrix in reverse order?
Show older comments
Hi.
Here is my simple example.
1 1 2
2 1 4
3 2 1
4 2 3
5 3 2
6 4 1
Suppose that column 2 and column 3 represent ID of agents, and column 1 represents unique pair ID.
Note that row 1 and row 3 are basically same and they have different pair ID.
I want to make the following matrix.
1 1 2 3
2 1 4 6
3 2 1 1
4 2 3 5
5 3 2 4
6 4 1 2
That is, I want to allow for the fact that the pairs in revesre order are the same.
Thank you.
Accepted Answer
More Answers (2)
Akira Agata
on 18 Jun 2021
How about the following way?
A = [...
1 1 2;...
2 1 4;...
3 2 1;...
4 2 3;...
5 3 2;...
6 4 1];
B = A(:,[3 2]);
[~, loc] = ismember(A(:,2:3),B,'rows');
A = [A, loc];
>> A
A =
1 1 2 3
2 1 4 6
3 2 1 1
4 2 3 5
5 3 2 4
6 4 1 2
1 Comment
Daeeun Bae
on 18 Jun 2021
If you use a table, you can use join.
A = [ 1 1 2
2 1 4
3 2 1
4 2 3
5 3 2
6 4 1];
ID = A(:,1);
Agent1 = A(:,2);
Agent2 = A(:,3);
TA = table(ID,Agent1,Agent2);
TB = table(ID,Agent2,Agent1);
% Join tables
joinedData = outerjoin(TA,TB,"Type","left","LeftKeys",["Agent1","Agent2"],...
"RightKeys",["Agent2","Agent1"],"MergeKeys",true)
1 Comment
Daeeun Bae
on 18 Jun 2021
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!