Why won't my "if then" statement keep my variable from dipping below zero?

So, I have a pretty simple code but I need to keep one variable (xg_z) from ever being below zero (the math will allow that to happen but physical reality will not). I thought I just needed an if-then (see in code; last 4 lines), but when I check it, it still lets the variable go below zero ... which screws up all the other calculations I need to make based on the value.
Any idea what I'm doing wrong?
if true
% code
% Constants:
density_1 = 2830;
zStart = 6000; % depth in crust (m)
zEnd = 0; % depth in crust (m)
rhoc = 2650; % density of the crust (kg m^-3)
xo = 0.045; % initial quantity of dissolved gas
rhom0 = density_1; % Initial density of the magma (or saturated density)
Q_in = 2.3; % Volume flux of magma into the system [m^3s^-1]
t_flux = 35.*24.*60.*60; % Days of magma flux into the system (35) [s]
mass_initial = density_1./(Q_in.*t_flux); % density / volume to get initial mass of magma
volume_final = (Q_in.*t_flux); % Volume actually cancels and is unecessary
% Depth range
z = zEnd:10:zStart; % Total range from chamber top to surface
z2 = 1200:10:6000; % Range from chamber to conduit
z3 = 0:10:1200; % Range from conduit to surface
% Constants:
rhog = 0.804; % density of gas [kg m^-3]
s = 4.11.*(10.^-6); % empirical coefficient depending on gas compositions of gas & melt
n = 0.5; % empirical coefficient depending on gas compositions of gas & melt
Psurface = 101325; % pressure at Earth's surface [Pa]
g = 9.8; % acceleration due to gravity [m s^-2]
rhow = 1000; % density of water [kg m^-3]
% Variables:
P_z = Psurface + (rhoc.*z.*g); % Pressure as a function of depth [Pa]
xg_z = xo - (s.*P_z.^n); % gas in vapor form as a function of z
if(xg_z<0)
xg_z=0;
end

 Réponse acceptée

James Tursa
James Tursa le 22 Juin 2015
Modifié(e) : James Tursa le 22 Juin 2015
You have a vector of values in xg_z, so you can use logical indexing to set those values that are less than 0 to 0. E.g.,
xg_z( xg_z < 0 ) = 0;

Plus de réponses (0)

Catégories

En savoir plus sur Fluid Dynamics dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by