How can I compare the multiple strings?
조회 수: 10 (최근 30일)
이전 댓글 표시
BHARAT CHARAN GOUD MARUPALLI
2021년 1월 10일
댓글: BHARAT CHARAN GOUD MARUPALLI
2021년 1월 12일
I am unable to compare the multiple strings at once to produce the required output. I have tried the following code. Here I would like to compare the input string and print the result from statements.
function result = select(sports)
sports = {'hockey','tennis'};_
if strcmpi(sports,'hockey');x=1;end
if strcmpi(sports,'cricket');x=2;end
if strcmpi(sports,'football');x=3;end
if strcmpi(sports,'tennis');x=4;end
result
end
댓글 수: 2
Rik
2021년 1월 10일
What is your actual goal? I presume sports={'hockey','tennis'} is actually meant to be the input to your function (instead of overwriting it). If so, what do you want the output to be?
채택된 답변
Image Analyst
2021년 1월 10일
Is this what you want (using ismember to find the index of the sport in the list of all the sports?
% Test script:
fprintf('Beginning to run %s.m ...\n', mfilename);
allSports = {'hockey','tennis', 'cricket', 'football', 'racing', 'golf', 'Cody'};
thisSport = 'Football';
result = select(thisSport, allSports)
fprintf('%s is sport #%d.\n', thisSport, result);
fprintf('Done running %s.m.\n', mfilename);
%======================================================
function result = select(thisSport, allSports)
thisSport = lower(thisSport);
allSports = lower(allSports);
[~, result] = ismember(thisSport, allSports)
end
댓글 수: 5
Image Analyst
2021년 1월 11일
Please attach the Sports table in a .mat file if you still need help
save('answers.mat', 'Sports');
By the way, select is a built-in function so you might want to call it something else, like SelectSport() instead.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

