if elseif giving too many outputs

1 次查看(过去 30 天)
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.

回答(2 个)

Image Analyst
Image Analyst 2017-9-25
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 个评论
Walter Roberson
Walter Roberson 2017-9-25
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 2017-9-25
So how would I change it to just evaluate which range the input H lies in and execute the function?

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2017-9-25
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.

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by