Is it possible to go from within a case in switch
to another case based on a condition?
Here is an example:
flag_1 = 'a'
flag_2 = 1;
x = 0;
switch flag_1
case 'a'
if flag_2 == 1
% go to otherwise
else
x = 1;
otherwise
x = 2;
end
If flag_2 == 1
I want to go from case 'a'
to otherwise
. Is it possible?
No, this is not possible. There’s no “goto” statement in MATLAB.
One solution is to put the code for the “otherwise” branch into a function, then call that function if your condition is met:
flag_1 = 'a'
flag_2 = 1;
x = 0;
switch flag_1
case 'a'
if flag_2 == 1
x = otherwise_case;
else
x = 1;
otherwise
x = otherwise_case;
end
function x=otherwise_case
% assuming this is more complex of course
x = 2;
end