Info

This question is closed. Reopen it to edit or answer.

If statement causes function to return only one value for an array of inputs

1 view (last 30 days)
Hello,
I have a problem that has been perplexing me for quite some time. I'm a novice at matlab, so I apologize if this is a silly question.
I'm trying to write a function that computes values of temperature, pressure, and density for any altitude below 90 kilometers. My function works fine for altitudes up to 11 km (the top of the first atmospheric layer, the thermosphere) but after that the function returns only one value.
So, say I pass a height vector
h1 = linspace (0, 11000)
[T,P,rho] = AtmosphereModel(h1)
Appears to behave normally, but
h2 = linspace (0, 20000)
[T,P,rho] = AtmosphereModel(h2)
returns a single value for the temperature and an array for the others. Why could that be?
I find that in
if (h <= 11000)
%Troposphere
T = TTrop_0 + LTrop.*h;
P = PTrop_0.*(T/TTrop_0).^(-g/(LTrop.*R));
elseif (h <= 20000)
%Tropopause
T = TTropPause;
P = PTropPause_0.*exp((-g./(R*T)) .* (h - 11000));
...
end
the first if statement is never executed, and the second is executed only once.
I am using Matlab r2014b. have attached my entire code for reference. Thanks for any help!

Answers (1)

Star Strider
Star Strider on 20 Nov 2015
I can’t run your code because I don’t have the constants, but this is one way to select for the specific values of ‘h’ that you can then use in your subsequent calculations:
h = linspace (0, 20000);
z1 = h(h <= 11000);
z2 = h((h > 11000) & (h <= 20000));
I added the extra condition in ‘z2’ here because otherwise it would be valid for the troposphere values as well as the tropopause. (And if I remember correctly, the dry adiabatic lapse rate only works for the troposphere.)
  2 Comments
Justin Rose
Justin Rose on 21 Nov 2015
Huh, that might work just as well. I'd still like to know why my original code doesn't work, but I'll try that. Thank you!
Star Strider
Star Strider on 21 Nov 2015
My pleasure!
Using if statements with vectors is a complicated problem. I experimented with your code and could not get it to work correctly with any of the functions used to compare vectors.
The real advantage of my code (you can rename z1 as htps for troposphere height and htpp for tropopause height to make them more meaningful) is that it selects the appropriate altitudes by vector, so you can then use them in vectorised code.

Community Treasure Hunt

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

Start Hunting!