How to do you appropriately define nested functions and variables within the function defining the differential equations for the ode45 solver?

2 views (last 30 days)
Hello I'm a graduate student who's relatively new to Matlab. Recently, I've been trying to build an ecological model that numerically evaluates a system of four first-order ode's using the ode45 function. I have done this successfully before, but this time several of the differential equations defined in the function handle of the solver (@odefun) are themselves dependent upon nested step-wise functions. When running the code, I have consistently gotten errors saying that the nested functions are undefined in the function that describes the differentials. To resolve this, I have tried to make all the nested variables global using the global command, but then the output of the function that describes the differentials is a vector of length 0, rather than a vector of length 4 that is required to integrate in the ode45 solver. While I'm probably not describing this right, I believe the problem lies in correctly communicating the output of the nested functions to the outer functions. Any help you can provide would be most appreciated. Thanks in advance. Here is the code I'm using. I apologize if this isn't formatted correctly.
function sealice_v1 ()
T = [0 2000];
F_init = 200000;
C_init = 0;
Z_init = 0;
L_init = 29;
% Parameters
omega = 6.7;
beta = 1;
sigma =0.15;
m = 0.6;
del = 0.0077;
chi = 0.033;
lambda = 0.08;
V = 8000;
R = 1;
L_max = 148;
tau=0.9;
parameters = [omega beta sigma m del chi lambda V R L_max tau];
[T N] = ode45(@odefun, T, [F_init; C_init; Z_init; L_init], parameters)
end
function f_prime = odefun(T, N, parameters)
global C F L intensity psi F_prime
F = N(1);
C = N(2);
Z = N(3);
L = N(4);
function intensityout = intensityfunc ()
intensityfunc = C ./(F*(0.0006821)*L^3.24)
function psiout=psifunc ()
if intensityfunc >= 0 && intensityfunc <= 0.01
psifunc = 1
elseif intensityfunc > 0.01
psifunc = 1.05+intensityfunc
end
end
end
intensity = intensityout
psi = psiout
function F_prime_out = F_prime_func ()
if intensity >= 0 && intensity <= 0.1;
F_prime_func = 0;
else
F_prime_func = -0.09*F;
end
end
F_prime = F_prime_out
omega = 6.7;
beta = 1;
sigma =0.15;
m = 0.6;
del = 0.0077;
chi = 0.033;
lambda = 0.08;
V = 8000;
R = 1;
L_max = 148;
tau=0.9;
C_prime = (1-m)*beta*((F*Z)/V)*(1-(intensity/sigma))-(del*C);
Z_prime = (0.5*R*omega*C)-(beta*((F*Z)/V)*(1-(intensity/sigma)))-(tau*Z)-(chi*Z);
L_prime = (lambda*(L_max-L))./psi;
f_prime = [F_prime; C_prime; Z_prime; L_prime]
end

Answers (0)

Categories

Find more on Numerical Integration and Differential Equations 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!