matlab - 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
解决方案
我认为您的意思是根据Grashof
,NGRASH
或SpecGrashof
中的哪一个来选择开关案例之一。您需要为此使用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 语句放在上面S
或L
上面。
推荐阅读
- python - 如何在字符串中使用 re.sub 更改路径,保持与扩展名相同的文件名
- android - 设计每行多个文本视图的可滚动列表
- javascript - 通过循环将对象添加到数组中的正确方法
- python - 为什么我的连接有一半时间被拒绝
- php - mod_rewrite 清除 URL 重写
- reactjs - 无法在服务器中“构建”项目
- http - 每次我使用 expo 客户端时,我的 http 网络都无法工作
- c++ - 计算自纪元以来的年份和当前年份的小时数
- azure - Azure Identity:尝试让 GetUserDelegationKey 与应用程序服务主体一起使用
- pandas - 在 Pandas 中从 DataFrame 制作散点图