using strcmpi in switch case

6 次查看(过去 30 天)
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

采纳的回答

meghannmarie
meghannmarie 2019-9-30
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 个)

类别

Help CenterFile Exchange 中查找有关 Grid Lines, Tick Values, and Labels 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by