Effacer les filtres
Effacer les filtres

How to use FOR loops to shorten IF statements?

3 vues (au cours des 30 derniers jours)
Rightia Rollmann
Rightia Rollmann le 13 Fév 2017
Commenté : Image Analyst le 13 Fév 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;

Réponse acceptée

Image Analyst
Image Analyst le 13 Fév 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 commentaires
Rightia Rollmann
Rightia Rollmann le 13 Fév 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;
Image Analyst
Image Analyst le 13 Fév 2017

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by