Borrar filtros
Borrar filtros

For loops with if statements

1 visualización (últimos 30 días)
John Woods
John Woods el 13 de Jun. de 2020
Respondida: Star Strider el 13 de Jun. de 2020
I have a for loop that I am trying to use to calculate the temperature at different elevations. It goes through the first if statement fine but after that, it stops. This is what I have:
e=0:200:55000;
for i=1:length(e)
if e(i)<=11000
T(i)=(-71.5/11000).*e(i)+15
elseif 11000<e(i)<20100
T(i)=-56.5;
elseif 20100<e(i)<32200
T(i)=(12/12100).*e(i)-76.434
elseif 32200<e(i)<47300
T(i)=(42/15100).*e(i)-134.063
else
T(i)=-2.5
end
end
What is wrong with my elseif and else statements?

Respuestas (1)

Star Strider
Star Strider el 13 de Jun. de 2020
The if conditions can only be evaluated as paired comparisons in order to get the result you want.
Try this:
e=0:200:55000;
for i=1:length(e)
if e(i)<=11000
T(i)=(-71.5/11000).*e(i)+15;
elseif (11000<e(i)) & (e(i)<20100)
T(i)=-56.5;
elseif (20100<e(i)) & (e(i)<32200)
T(i)=(12/12100).*e(i)-76.434;
elseif (32200<e(i)) & (e(i)<47300)
T(i)=(42/15100).*e(i)-134.063;
else
T(i)=-2.5;
end
end
This has to do with the way logical comparisons are evaluated.
.

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