Tables: Inner Join using Key 1 or Key 2

2 ビュー (過去 30 日間)
Dom
Dom 2023 年 10 月 26 日
コメント済み: Voss 2023 年 10 月 26 日
It appears that one can do an inner join in Matlab using key 1 and key 2 - I cannot sem to find a command for Key 1 or Key 2.
Here is some sample data:
i={'A'; 'B';'C';'D';'C';'D';'D';'B';'A'};
j={'B'; 'C';'D';'A';'B';'B';'C';'D';'C'};
i=categorical(i);
j=categorical(j);
v=[10;20;30;40;50;60;70;80;90];
T=table(i,j,v);
i={'A'; 'B'};
i=categorical(i);
j=i;
Tk=table(i,j);
Now I have two tables T and Tk (Tk contains keys).
I would like to join the two tables using two keys T.i=Tk.i or T.j=Tk.j
I could do these separately, for example:
T1=innerjoin(T,Tk,'Keys','i');
T2=innerjoin(T,Tk,'Keys','j');
But there is no way to vertically stack the two tables T1 and T2
Basically the final result should look like this:
i j v
A B 10
B C 20
B D 80
A C 90
A B 10
D A 40
C B 50
D B 60
Thank you,

採用された回答

Voss
Voss 2023 年 10 月 26 日
編集済み: Voss 2023 年 10 月 26 日
i={'A';'B';'C';'D';'C';'D';'D';'B';'A'};
j={'B';'C';'D';'A';'B';'B';'C';'D';'C'};
i=categorical(i);
j=categorical(j);
v=[10;20;30;40;50;60;70;80;90];
T=table(i,j,v)
T = 9×3 table
i j v _ _ __ A B 10 B C 20 C D 30 D A 40 C B 50 D B 60 D C 70 B D 80 A C 90
i={'A';'B'};
i=categorical(i);
j=i;
result = [T(ismember(T.i,i),:); T(ismember(T.j,j),:)]
result = 8×3 table
i j v _ _ __ A B 10 B C 20 B D 80 A C 90 A B 10 D A 40 C B 50 D B 60
Or if you don't care about that specific row ordering or repeating the row where both T.i and T.j are in {'A';'B'}:
% result = T(ismember(T.i,i) | ismember(T.j,j),:) % alternative
result = T(any(ismember([T.i,T.j],i),2),:) % works only because i == j
result = 7×3 table
i j v _ _ __ A B 10 B C 20 D A 40 C B 50 D B 60 B D 80 A C 90
  2 件のコメント
Dom
Dom 2023 年 10 月 26 日
Thank you Voss. Much appreciated. Thanks also for including the 7x3 alternative which excludes the duplicated row: A B 10.
Voss
Voss 2023 年 10 月 26 日
You're welcome!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTables についてさらに検索

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by