フィルターのクリア

How to use FOR loops to shorten IF statements?

3 ビュー (過去 30 日間)
Rightia Rollmann
Rightia Rollmann 2017 年 2 月 13 日
コメント済み: Image Analyst 2017 年 2 月 13 日
I have a if structure with 19 elseif parts. Is there any way to use a for loop to write elseif once and control it by a for loop?
If expression1 == 1
statement1
elseif expression1 == 2
statement1 + 1
.
.
.
elseif expression1 == 20
statement1 + 19
end;

採用された回答

Image Analyst
Image Analyst 2017 年 2 月 13 日
You can use a switch statement but it doesn't reduce the number of lines - in fact it makes it one more.
Since the expression evaluates to an integer, and (I guess) you're adding the very same integer to the "statement1" variable, you can replace the whole "if" structure with this:
statement1 = statement1 + expression1 - 1 % Add (expression1 value - 1) to statement1 variable.
  2 件のコメント
Rightia Rollmann
Rightia Rollmann 2017 年 2 月 13 日
Thank you for your suggestion. Could you please give me an concrete example for the sample below:
if i==1
j = 1;
elseif i==2
j=2;
elseif i==3
j=3;
end;
Image Analyst
Image Analyst 2017 年 2 月 13 日
Simply:
j = i;

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by