Info

This question is closed. Reopen it to edit or answer.

match on a string

1 view (last 30 days)
Sourangsu Chowdhury
Sourangsu Chowdhury on 22 Dec 2017
Closed: MATLAB Answer Bot on 20 Aug 2021
I have a phone book directory with country codes for all the countries in the format
a = {
886 TW
992 TJ
255 TZ
66 TH
690 TK
676 TO
1868 TT
216 TN
90 TR
993 TM
1649 TC}
I have another data with arbitrary country codes like
scode=[90 992 216]
I want to match the data such that my output is
xxx= 90 TR
992 TJ
216 TN
I wrote a code but it does not seem to work for the character strings
clc
clear
[~,~, a]= xlsread('D:\Country-codes.xls','a','C3:D271');
scode= xlsread('D:\COP 18.xlsx','Sheet3','A2:A401');
t=str2num((a(:,2));
scode=scode';
bsxfun(@minus,t(:,1),scode);
[~,minRow] = min(abs(bsxfun(@minus,t(:,1),scode)));
xxx = [ scode.', t(minRow,2:end) ];

Answers (2)

Matt J
Matt J on 22 Dec 2017
This would be a good application of a container.Map
map=container.Map([a{:,1}],[a{:,2}]);
xxx=arrayfun(@(i) map(i), scode(:),'uni',0);

Stephen23
Stephen23 on 22 Dec 2017
Edited: Stephen23 on 22 Dec 2017
Putting numeric data into a cell array makes it harder to process. Converting to numeric using str2double is reccomended rather than using str2num. Once you put those numeric scalars into a numeric vector then this task is trivial using ismember:
a = {...
'886' 'TW'
'992' 'TJ'
'255' 'TZ'
'66' 'TH'
'690' 'TK'
'676' 'TO'
'1868' 'TT'
'216' 'TN'
'90' 'TR'
'993' 'TM'
'1649' 'TC'};
scode = [90,992,216];
[~,idx] = ismember(scode,str2double(a(:,1)))
out = a(idx,:)
giving:
out =
'90' 'TR'
'992' 'TJ'
'216' 'TN'

Community Treasure Hunt

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

Start Hunting!