Match strings from 2 tables

4 Ansichten (letzte 30 Tage)
SChow
SChow am 18 Feb. 2020
Kommentiert: SChow am 18 Feb. 2020
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

Akzeptierte Antwort

Stephen23
Stephen23 am 18 Feb. 2020
Bearbeitet: Stephen23 am 18 Feb. 2020
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

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by