using strcmpi in switch case

11 visualizaciones (últimos 30 días)
Natalie Huynh
Natalie Huynh el 30 de Sept. de 2019
Editada: Natalie Huynh el 30 de Sept. de 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

Respuesta aceptada

meghannmarie
meghannmarie el 30 de Sept. de 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

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by