How can I extract unique pairs of matrix in reverse order?

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

Siwon Ryu
Siwon Ryu on 18 Jun 2021
I think you can use join after converting your array into tables.
First, find unique pairs of the combination of the first three columns. This procedure prevent the changes in total number of rows after joining.
And then, right-join (Because ID table only includes distinct values of two IDs, both inner and outer join would work) the unique ID table to the original table on two keys: column2 and 3 in the reverse order. See this:
A = [1 1 2; 2,1,4;3,2,1;4,2,3;5,3,2;6,4,1]
% Find unique pairs of Indices
A_ID = unique(A(:,1:3),'rows')
% Convert to Tables
T_ID = array2table(A_ID)
T_ID.Properties.VariableNames(1:3) = {'ID','ID1','ID2'}
T_ID_tg = array2table(A(:,[1,3,2]))
T_ID_tg.Properties.VariableNames(1:3) = {'ID','ID1','ID2'}
% Join
T = join(T_ID_tg, T_ID,'Keys',{'ID1','ID2'})
% Convert to array
A_result = T{:,:}

More Answers (2)

Akira Agata
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

Cris LaPierre
Cris LaPierre 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)
joinedData = 6×4 table
ID_TA Agent1 Agent2 ID_TB _____ ______ ______ _____ 1 1 2 3 2 1 4 6 3 2 1 1 4 2 3 5 5 3 2 4 6 4 1 2

Categories

Find more on Structures 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!