Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

match on a string

조회 수: 1 (최근 30일)
Sourangsu Chowdhury
Sourangsu Chowdhury 2017년 12월 22일
마감: MATLAB Answer Bot 2021년 8월 20일
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) ];

답변 (2개)

Matt J
Matt J 2017년 12월 22일
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 2017년 12월 22일
편집: Stephen23 2017년 12월 22일
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!

Translated by