Filter löschen
Filter löschen

How to use FOR loops to shorten IF statements?

3 Ansichten (letzte 30 Tage)
Rightia Rollmann
Rightia Rollmann am 13 Feb. 2017
Kommentiert: Image Analyst am 13 Feb. 2017
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;

Akzeptierte Antwort

Image Analyst
Image Analyst am 13 Feb. 2017
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 Kommentare
Rightia Rollmann
Rightia Rollmann am 13 Feb. 2017
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;

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by