Borrar filtros
Borrar filtros

How to use FOR loops to shorten IF statements?

3 visualizaciones (últimos 30 días)
Rightia Rollmann
Rightia Rollmann el 13 de Feb. de 2017
Comentada: Image Analyst el 13 de Feb. de 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;

Respuesta aceptada

Image Analyst
Image Analyst el 13 de Feb. de 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 comentarios
Rightia Rollmann
Rightia Rollmann el 13 de Feb. de 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;

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by