Match strings from 2 tables

3 vues (au cours des 30 derniers jours)
SChow
SChow le 18 Fév 2020
Commenté : SChow le 18 Fév 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

Réponse acceptée

Stephen23
Stephen23 le 18 Fév 2020
Modifié(e) : Stephen23 le 18 Fév 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
  1 commentaire
SChow
SChow le 18 Fév 2020
Thanks a lot Stephen!!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Error Detection and Correction dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by