1

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?

Dev-iL
  • 23,742
  • 7
  • 57
  • 99
Afaf
  • 59
  • 5
  • 2
    Is your actual list of cases more complex? Because this example doesn't really need the `switch`. – beaker Jul 16 '21 at 14:50

3 Answers3

4

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
Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
2

Similar to Cris' answer, you could set a flag, and have a simpler conditional based on that flag after the switch:

flag_1 = 'a'
flag_2 = 1;

x = 0;

otherwise_case = false;
switch flag_1
    case 'a'
       if flag_2  == 1
          otherwise_case = true;
       else 
          x = 1;
    otherwise
       otherwise_case = true;
end

if otherwise_case
   % assuming this is more complex of course
   x = 2;
end

This is simpler if, for instance, the otherwise_case function would have lots of required inputs which are already available in the current scope when using the flag approach instead.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
2

For completeness, I'm going to mention the "early bailout" approach. Basically, you put your switch inside a try/catch:

try
  switch flag_1
      case 'a'
         if flag_2  == 1
            throw(...)
         else 
            x = 1;
      otherwise
         throw(...)
  end
catch ME
  % otherwise case, if exception is as expected
end

I should note that the other answers are likely more suitable for the present problem. This approach is useful when you have multiple loops or internal functions within the case, and you want to quickly exit all of them and reach the "otherwise". Note that when doing this you should check within the catch clause that the exception is as you expect (example), to avoid legitimate issues that might arise in the cases' logic.

Dev-iL
  • 23,742
  • 7
  • 57
  • 99