Clear Filters
Clear Filters

if elseif giving too many outputs

1 view (last 30 days)
Stenila  Simon
Stenila Simon on 25 Sep 2017
Answered: Walter Roberson on 25 Sep 2017
Hi everyone, I'm trying to finish writing a matlab code that will read an input for a certain altitude, and then calculate a couple of properties based on that altitude. The thing is, for each range of altitude, the values for the variables used in calculating these properties changes, so I have to reassign each variable new values based on the range this input falls under.
Here is my code:
if (H <= 11000)
Hbi = 0;
deltai = 1;
KTi = -6.5;
Tbi = 288.15;
LinP = (deltai.*(1+((KTi/Tbi).*(H-Hbi))).^(expterm/KTi));
ConstP = (deltai.*exp(-((expterm)/Tbi).*(H-Hbi)));
fprintf('Linear pressure ratio = %f\n', LinP);
elseif (H < 20000)
Hbi= 11000;
deltai = 0.22336;
KTi = 0;
Tbi = 216.65;
LinP = (deltai.*(1+((KTi/Tbi).*(H-Hbi))).^(expterm/KTi));
ConstP = (deltai.*exp(-((expterm)/Tbi).*(H-Hbi)));
fprintf('Linear pressure ratio = %f\n', LinP);
end
Please note that "expterm", etc. has already been established, so that's not my issue. There is no error when I run it. When I run it, it asks for the input, and when I put in the input, it gives me like ten thousand different values.

Answers (2)

Image Analyst
Image Analyst on 25 Sep 2017
That's because LinP is an array of like ten thousand elements, and this:
fprintf('Linear pressure ratio = %f\n', LinP);
will repeat for every one of those ten thousand elements. LinP is 10,000 values because either H or expterm is 10,000 values.
  2 Comments
Walter Roberson
Walter Roberson on 25 Sep 2017
Note that if H is a vector, then
if (H <= 11000)
is the same as
if all(H(:) <= 11000)
which would be false if even one value of H > 11000.
Stenila  Simon
Stenila Simon on 25 Sep 2017
So how would I change it to just evaluate which range the input H lies in and execute the function?

Sign in to comment.


Walter Roberson
Walter Roberson on 25 Sep 2017
LinP = nan(size(H));
ConstP = nan(size(H));
mask = H <= 11000;
Hbi = 0;
deltai = 1;
KTi = -6.5;
Tbi = 288.15;
LinP(mask) = (deltai.*(1+((KTi/Tbi).*(H(mask)-Hbi))).^(expterm/KTi));
ConstP(mask) = (deltai.*exp(-((expterm)/Tbi).*(H(mask)-Hbi)));
mask = H > 11000 & H < 20000;
Hbi= 11000;
deltai = 0.22336;
KTi = 0;
Tbi = 216.65;
LinP(mask) = (deltai.*(1+((KTi/Tbi).*(H(mask)-Hbi))).^(expterm/KTi));
ConstP(mask) = (deltai.*exp(-((expterm)/Tbi).*(H(mask)-Hbi)));
plot(H, LinP)
You did not have a final "elseif" giving a value for the situation where H was not in either range, so I assigned NaN for that case.

Categories

Find more on Entering Commands in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!