Switch Case or if-else?

65 ビュー (過去 30 日間)
Sean Rubino
Sean Rubino 2021 年 5 月 21 日
回答済み: Stephen23 2023 年 7 月 18 日
Hello,
I'm writing a script which calculates a value of "R" which is then compared to several inequality limits. The limits are:
R <= 1.2
1.2 < R <= 1.45
1.45 < R <= 1.66
1.66 < R <= 1.93
R > 1.93
Once R satisfies the conditional statement a subroutine is prompted and 1 of 5 subsequent scripts is run.
Is switch case or if-else better for this?

採用された回答

Atsushi Ueno
Atsushi Ueno 2021 年 5 月 21 日
Switch statement cannot judge the range of R. It may be possible but it must be very tricky.
  • A case_expression cannot include relational operators such as < or > for comparison against the switch_expression. To test for inequality, use if, elseif, else statements.
if (R <= 1.2)
disp('if-else condition 1');
elseif (R <= 1.45)
disp('if-else condition 2');
elseif (R <= 1.66)
disp('if-else condition 3');
elseif (R <= 1.93)
disp('if-else condition 4');
else % R > 1.93
disp('if-else condition 5');
end
I would use this method.
index = find(R <= [1.2 1.45 1.66 1.93 inf], 1, 'first');
disp(['if-else condition ' num2str(index)]);
  4 件のコメント
Atsushi Ueno
Atsushi Ueno 2021 年 5 月 21 日
Thank you.
I don't know what script you are writing is. Is it MATLAB function? or other language script?
Please show something about what you are writing, at least interface...
Sean Rubino
Sean Rubino 2021 年 5 月 21 日
if R <= 1.2;
disp('Uniform Illumination');
Uni_Ill
elseif R <= 1.45;
disp('Cosine Illumination');
Cos_Ill
elseif R <= 1.66;
.
.
.
MATLAB script. I got it to work out for what I am doing. I'm sure I'll be tweaking things but this is a start.

サインインしてコメントする。

その他の回答 (2 件)

Dyuman Joshi
Dyuman Joshi 2021 年 5 月 21 日
if-else would be better in this case because you have a range of values of R (a variable).
switch is useful when you have descrete values of a variable.

Stephen23
Stephen23 2023 年 7 月 18 日
"Switch statement cannot judge the range of R. It may be possible but it must be very tricky."
switch true
case R <= 1.2
disp('condition 1');
case R <= 1.45
disp('condition 2');
case R <= 1.66
disp('condition 3');
case R <= 1.93
disp('condition 4');
otherwise % R > 1.93
disp('condition 5');
end

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

製品


リリース

R2018a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by