Understanding switch and case expressions
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
a = 'hi';
switch a
case {'hi','hello'}
disp('hi, hello')
case 'hi'
disp('hi')
end
When executing this code, the result is hi, hello. This does not make sense to me. If a = 'hi', then according to the case 'hi' shouldn't the result just be hi. Why is it hi, hello?
0 Kommentare
Akzeptierte Antwort
Ryan Livingston
am 12 Mär. 2013
Bearbeitet: Ryan Livingston
am 12 Mär. 2013
The cases are checked in order. Since a = 'hi' and 'hi' is in the first case, that one is chosen.
Using a cell array:
case {'hi', 'hello'}
disp('hi, hello');
means "pick this case if "a" is either 'hi' or 'hello'. It is somewhat equivalent to saying:
if strcmp(a,'hi') || strcmp(a,'hello')
disp('hi, hello');
1 Kommentar
Shashank Prasanna
am 12 Mär. 2013
Joe this behavior is explained in the doc:
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!