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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Error Detection and Correction 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by