For loops with if statements

2 views (last 30 days)
John Woods
John Woods on 13 Jun 2020
Answered: Star Strider on 13 Jun 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?

Answers (1)

Star Strider
Star Strider on 13 Jun 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.
.

Categories

Find more on Environment and Settings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!