MATLAB Answers

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

4 ビュー (過去 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
  1 件のコメント
Daeeun Bae
Daeeun Bae 2021 年 6 月 18 日
Great. Thank you!

サインインしてコメントする。


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
  1 件のコメント
Daeeun Bae
Daeeun Bae 2021 年 6 月 18 日
Thank you!

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by