For loops with if statements

1 次查看(过去 30 天)
John Woods
John Woods 2020-6-13
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?

回答(1 个)

Star Strider
Star Strider 2020-6-13
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.
.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by