Azzera filtri
Azzera filtri

How to use FOR loops to shorten IF statements?

3 visualizzazioni (ultimi 30 giorni)
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;

Risposta accettata

Image Analyst
Image Analyst il 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 Commenti
Rightia Rollmann
Rightia Rollmann il 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;

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by