首页 > 解决方案 > Get a switch case to call on switch case instead of running through all of them

问题描述

Below you can see my code. When I run this I get answers from all three switch statements. I want only one answer from one of the switch statements and for the other two to be ignored. How can I accomplish this?

function grashofrough(a, b, c, d)

% The variables a,b,c, and d are variables to 
%   represent the length of each length
Lengths = [ a b c d ]; 
S=min(Lengths);
L=max(Lengths);

%This will direct to 'Grashof' cases
Grashof = L+S < sum(Lengths)-(S+L); 

%This will direct to 'Non-grashof' cases
NGRASH = L+S > sum(Lengths)-(S+L);

%This will direct to 'Special Grashof' cases
SpecGrashof = L+S == sum(Lengths)-(S+L); 



switch Grashof 
    case S == a
        disp("GCCC")
    case S == b
        disp("GCRR")
    case S == c
        disp("GRCR")
    case S == d
        disp("GRRC")
    otherwise
        return
end

switch NGRASH
    case L == a
        disp("RRR1")
    case L == b
        disp("RRR1")
    case L == c
        disp("RRR3")
    case L == d
        disp("RRR4")
    otherwise
        return
end

switch SpecGrashof
    case S == a
        disp("SCCC")
    case S == b
        disp("SCRR")
    case S == c
        disp("SRCR")
    case S == d
         disp("SRRC")
    otherwise
         return
end

标签: matlabswitch-statement

解决方案


我认为您的意思是根据Grashof,NGRASHSpecGrashof中的哪一个来选择开关案例之一。您需要为此使用if声明。

您的使用switch不正确,参数switch是一个变量,各种情况是该变量的可能值。我建议你阅读文档

这是你打算写的:

if Grashof
  switch S
    case a
      disp("GCCC")
    case b
      disp("GCRR")
    case c
      disp("GRCR")
    case d
      disp("GRRC")
    otherwise
      return
  end
elseif NGRASH
  switch L
    case a
      disp("RRR1")
    case b
      disp("RRR1")
    case c
      disp("RRR3")
    case d
      disp("RRR4")
    otherwise
      return
  end
else % SpecGrashof must be true here, no need to test for it
  switch S
    case a
      disp("SCCC")
    case b
      disp("SCRR")
    case c
      disp("SRCR")
    case d
       disp("SRRC")
    otherwise
       return
  end
end

但是考虑到您对这三种情况的定义:

Grashof = L+S < sum(Lengths)-(S+L); %This will direct to 'Grashof' cases
NGRASH = L+S > sum(Lengths)-(S+L); %This will direct to 'Non-grashof' cases
SpecGrashof = L+S == sum(Lengths)-(S+L); %This will direct to 'Special Grashof' cases

您还可以打开以下值的符号:

K = (L+S) - (sum(Lengths)-(S+L));
switch sign(K)
  case -1 % Grashof cases
    % ...
  case 1 % NGRASH cases
    % ...
  case 0 % Special Grashof cases
    % ...
end

在每种情况下,您都将 switch 语句放在上面SL上面。


推荐阅读