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

조회 수: 7 (최근 30일)
Daeeun Bae
Daeeun Bae 2021년 6월 18일
댓글: Daeeun Bae 2021년 6월 18일
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.

채택된 답변

Siwon Ryu
Siwon Ryu 2021년 6월 18일
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{:,:}

추가 답변 (2개)

Akira Agata
Akira Agata 2021년 6월 18일
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 2021년 6월 18일
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

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by