切换案例:从另一个案例转到 'otherwise'

switch case: go to 'otherwise' from within another case

是否可以根据条件从 switch 中的一个案例转到另一个案例? 这是一个例子:

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

如果flag_2 == 1我想从case 'a'升到otherwise。可能吗?

不,这是不可能的。 MATLAB 中没有“goto”语句。

一个解决方案是将“否则”分支的代码放入一个函数中,然后在满足条件时调用该函数:

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

类似于,你可以设置一个标志,并在切换后根据该标志有一个更简单的条件:

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

例如,如果 otherwise_case 函数有很多必需的输入,当使用标志方法时,这些输入在当前范围内已经可用。

为了完整起见,我要提到“早期救助”方法。基本上,您将 switch 放在 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

我应该注意到 其他答案可能更适合当前的问题。当案例中有多个循环或内部函数,并且您想快速退出所有循环并到达“否则”时,此方法很有用。请注意,执行此操作时,您应该在 catch 子句中检查异常是否符合您的预期 (example),以避免案例逻辑中可能出现的合法问题。