using strcmpi in switch case
6 views (last 30 days)
Show older comments
Natalie Huynh
on 30 Sep 2019
Edited: Natalie Huynh
on 30 Sep 2019
I was able to do this using with an if-else statement (as shown below), but am unsure of how to convert it to a switch case. I know that I could put every single permutation of each case name in an array, but I wanted to know if there was an easier way to do that.
function state = stateAbbreviation(inputStr)
origState = upper(inputStr);
alabamaStr = 'Alabama';
alabamaAbrev = 'AL';
alaskaStr = 'Alaska';
alaskaAbrev = 'AK';
arizonaStr = 'Arizona';
arizonaAbrev = 'AZ';
kansasStr = 'Kansas';
kansasAbrev = 'KS';
caliStr = 'California';
caliAbrev = 'CA';
if strcmpi(origState, alabamaStr)
state = "AL";
elseif strcmpi(origState, alabamaAbrev)
state = "Alabama";
elseif strcmpi(origState, alaskaStr)
state = "AK";
elseif strcmpi(origState, alaskaAbrev)
state = "Alaska";
elseif strcmpi(origState, arizonaStr)
state = "AZ";
elseif strcmpi(origState, arizonaAbrev)
state = "Arizona";
elseif strcmpi(origState, kansasStr)
state = "KS";
elseif strcmpi(origState, kansasAbrev)
state = "Kansas";
elseif strcmpi(origState, caliStr)
state = "CA";
elseif strcmpi(origState, caliAbrev)
state = "California";
else
disp('Unknown')
end
end
0 Comments
Accepted Answer
meghannmarie
on 30 Sep 2019
For a switch statement try this:
function state = stateAbbreviation(inputStr)
switch upper(inputStr)
case 'ALASKA'
state = 'AK';
case 'AK'
state = 'Alaska';
case 'ALABAMA'
state = 'AL';
case 'AL'
state = 'Alabama';
otherwise
disp('Unknown State')
end
end
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!