Match strings from 2 tables

5 ビュー (過去 30 日間)
SChow
SChow 2020 年 2 月 18 日
コメント済み: SChow 2020 年 2 月 18 日
Hi, I have 2 tables example:
TA=
'Name' 'Code'
'AFG' 120
'CAN' 210
'BER' 121
'FIJ' 910
'KOS' 991
'HAW' 101
'CHN' 211
TB=
'Name' 'Value'
'AFG' 0.5
'CAN' 1.2
'BER' 2.1
'FIJ' 9.1
'CHN' 0.2
'HAW' 1.6
I need a table TC in order of TA but containg the corresponding value from TB
'Name' 'Code' 'Value'
'AFG' 120 0.5
'CAN' 210 1.2
'BER' 121 2.1
'FIJ' 910 9.1
'KOS' 991 NaN
'HAW' 101 1.6
'CHN' 211 0.2
I know I need to use the ismember function for this, but not sure how to implement it here

採用された回答

Stephen23
Stephen23 2020 年 2 月 18 日
編集済み: Stephen23 2020 年 2 月 18 日
Method one: outerjoin (TC rows may be in a different order to TA):
>> TC = outerjoin(TA,TB,'MergeKeys',true)
TC =
Name Code Value
_____ ____ _____
'AFG' 120 0.5
'BER' 121 2.1
'CAN' 210 1.2
'CHN' 211 0.2
'FIJ' 910 9.1
'HAW' 101 1.6
'KOS' 991 NaN
Method two: outerjoin (TC rows are in the same order as TA):
>> [TC,idx] = outerjoin(TA,TB,'MergeKeys',true);
>> [~,idy] = sort(idx);
>> TC = TC(idy,:)
TC =
Name Code Value
_____ ____ _____
'AFG' 120 0.5
'CAN' 210 1.2
'BER' 121 2.1
'FIJ' 910 9.1
'KOS' 991 NaN
'HAW' 101 1.6
'CHN' 211 0.2
Method three: ismember (TC rows are in the same order as TA):
>> TC = TA;
>> TC{:,'Value'} = NaN;
>> [X,Y] = ismember(TA.Name,TB.Name);
>> TC.Value(X) = TB.Value(Y(X))
TC =
Name Code Value
_____ ____ _____
'AFG' 120 0.5
'CAN' 210 1.2
'BER' 121 2.1
'FIJ' 910 9.1
'KOS' 991 NaN
'HAW' 101 1.6
'CHN' 211 0.2
  1 件のコメント
SChow
SChow 2020 年 2 月 18 日
Thanks a lot Stephen!!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeError Detection and Correction についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by