Matlab ode45. How to change a parameter inside it while calling it? - function

I'm new with Matlab. I hope you can help me.
I have to solve a system of ODEs using ODE45 function. Here is the function which describes my equitions.
function dNdt = rateEquations(t, y)
%populations of corresponding state
Ng = y(1);
Ns = y(2);
Nt = y(3);
%All constants used are dropped for the sake of easy reading.
Note the parameter F.
%rate equations
dNs = s0 * Ng * F - Ns/ t_S1;
dNt = Ns / t_ISC - Nt / t_T1;
dNg = -dNt - dNs;
dNdt = [dNg; dNs; dNt];
end
Then, in my script .m-file i call the ode45 function in 'for loop'. During each iteration i have to change the parameter F and pass it to my 'rateEquations' - function. But i don't know how to realize it.
for T = Tmin: dt : Tmax
%initial conditions
initialConditions = [N0 0 0];
timeSpan = [T T+dt];
before calling ODE45 F is to be changed.
[t,N] = ode45('rateEquations', timeSpan, initialConditions)
and so on ...
end
Thanks in advance.

You want make F an argument of your derivative function and pass the right anonymous function to ode45:
[t,N] = ode45(#(t,y) rateEquations(t,y,F), timeSpan, initialConditions)

Related

Scilab - define a function inside another one

I want to define a function that takes an input n and gives back the function f defined by f(x) = x^n.
So I wrote the following piece of code on Scilab:
function [f]=monomial(n)
function [z] = g(x)
z = x^n
endfunction
f = g
endfunction
Unfortunately when I evaluate monomial(3)(2) I get 32. whereas it should be 8.
I hope someone could point out where I have gone wrong when writing this function.
Could somebody help me please?
I cleared all variables and reran the code and it told me that n is not defined within g, therefore is there a way to overcome this problem?
the more secure way to do this is by using deff :
function [f]=monomial(n)
f = deff('z=g(x)','z=x^'+string(n));
endfunction
otherwise n could be polluted by current scope
--> monomial(2)(8)
ans =
64.

Uppercase in name of a function in Julia

I am fairly new to Julia and got confused with the following code. After a function LucasTree is defined, it is used again as lt. Does Julia have some kind of role where I can recall a function using the uppercase abbreviation? If so, where can I find a nice reference for this feature?
function LucasTree(;γ = 2.0,
β = 0.95,
α = 0.9,
σ = 0.1,
grid_size = 100)
ϕ = LogNormal(0.0, σ)
shocks = rand(ϕ, 500)
# build a grid with mass around stationary distribution
ssd = σ / sqrt(1 - α^2)
grid_min, grid_max = exp(-4ssd), exp(4ssd)
grid = range(grid_min, grid_max, length = grid_size)
# set h(y) = β * int u'(G(y,z)) G(y,z) ϕ(dz)
h = similar(grid)
for (i, y) in enumerate(grid)
h[i] = β * mean((y^α .* shocks).^(1 - γ))
end
return (γ = γ, β = β, α = α, σ = σ, ϕ = ϕ, grid = grid, shocks = shocks, h = h)
end
function lucas_operator(lt, f)
# unpack input
#unpack grid, α, β, h = lt
z = lt.shocks
Af = LinearInterpolation(grid, f, extrapolation_bc=Line())
Tf = [ h[i] + β * mean(Af.(grid[i]^α .* z)) for i in 1:length(grid) ]
return Tf
end
No, this does not exist. It would be too nonunique to be practical, and moreover function names in Julia by convention should be entirely lowercase (structs/types can be CamelCase, but not functions, with the possible exception of constructors*).
In any case, all that is happening here in the code you have posted is that the function lucas_operator takes two arguments, lt and f, which can then be used within that lucas_operator function. These could in principle be anything, and regardless of what they are named outside the scope of the function, they will be named lt and f within the scope of the function. So for example:
function example(foo, bar)
return foo(2*bar)
end
if you then call
example(somereallylongfunctionname, somevariable)
then that will return the equivalent of
somereallylongfunctionname(2*somevariable)
or similarly
example(SomeImproperlyCapitalizedFunction, somevariable)
# equivalent to SomeImproperlyCapitalizedFunction(2*somevariable)
in either case, regardless of its name outside the scope of the example function, the first argument passed to the function will be known as foo within the function.
* Aside about constructors: that would be a function that is used to construct a custom type. This doesn't quite do that, but it does return an instance of a NamedTuple which then seems to be treated somewhat like a type/struct in the subsequent code, so perhaps it could be counted as a constructor.

How to define a function with a parameter in it in Octave?

I am trying to define a function with a predefined variable, and Octave says that the variable was not defined. I am trying to run the following code in Octave,
q = 5;
function w = tointegrate(x)
w = 2 * q * sin(x);
endfunction
[ans, ier, nfun, err] = quad("tointegrate", -10*q, 10*q);
ans
Octave gives the error
error: 'q' undefined near line 3 column 10
error: quad: evaluation of user-supplied function failed
How to fix this error?
You are expecting 'commandline functions' in octave to have lexical scope, but this is simply not the case.
If all of this was inside a function, and you defined a nested function, it would work as you expect. But 'commandline functions' like this are treated as if they are in their own file, and have no knowledge of the workspace in which they've been defined.
In this particular case, since your function is effectively a one-liner, you can get the effect you want by making it a function handle instead, which 'does' capture the local workspace. I.e. this will work
q = 5;
tointegrate = #(x) 2 * q * sin(x);
[ans, ier, nfun, err] = quad("tointegrate",-10 *q ,10*q);
Note, however, that 'q' will have the value it had at the time it was captured. I.e. if you update q dynamically, its value will not be updated in the function handle.
Otherwise, for more complex functions, the solution is really to pass it as a parameter (or to access it as a global etc).
You can solve this by having q be a parameter to the function, then creating an anonymous function to call quad, like so:
function w = tointegrate(x, q)
w = 2 * q * sin(x);
endfunction
q = 5;
[ans, ier, nfun, err] = quad(#(x)tointegrate(x,q), -10*q, 10*q);
ans

Writing a function m-file in MATLAB

I am a beginner to coding and I need to write a function.m file for use with Newton's Method. I am having trouble defining the function, where r is radius and p is density:
f(theta) = ((r^2)/2)*((2*pi*p)-(theta - sin(theta)*p))
where radius r = 30cm and density p = 0.82 grams per cm^3
So far, I have written:
function y = f1(theta)
r = 0.3;
p = 0.82;
y = (r^2)/2*(2*pi*p - (theta - sin(theta)*p));
Things I am having trouble with:
Problem defining r and p. Getting an error:
Undefined function or variable 'r'
Having trouble plotting the function.
Things I want to do:
Plot the function to see where the roots are.
Be able to evaluate the function for a given theta.
All help is appreciated. Thank you!
i tried your code without changing. i named the M-file as f1 and executed the function in command line it is working.
function y = f1(theta)
r = 0.3;
p = 0.82;
y = (r^2)/2*(2*pi*p - (theta - sin(theta)*p));
i am getting the output as below
f=f1(45)
f =
-1.7618
this tells that there is no problem in your function. see for some other reason. if you could give your whole code it would be better to diagnose.
This could be done using an anonymous function
r=0.3;
p=0.82;
f=#(theta) (r^2)/2*(2*pi*p-theta+p*sin(theta));
then to evaluate the function just use eg: f(1), and to plot it, for example:
angles=0:.01:pi;
plot(angles,f(angles))
If you don't want to use an anonymous function, then use
function funcVal=func(angles)
r=0.3;
p=0.82;
funcVal=(r^2)/2*(2*pi*p-angles+p*sin(angles));
end
and call it by
angles=0:.01:pi;
plot(angles,func(angles))

Passing additional arguments through function handle in Matlab

I have a function to optimize, say Function, in Matlab. This function depends on variables (say x) over which I want to optimize and one parameter (say, Q) which does not need to be optimized.Hence, the function Function(x,Q). In other words, I have an array of values for Q and want to find optimal x values for each Q. However, I cannot find a way how to pass those Q values when using function handle #Function in optimization function.
So, my question is how to pass those Q values when using function handle in optimization functions, for example fmincon(#Function,x0,A,b)?
Try using anonymous function:
x = cell( 1, numel(Q) );
for qi = 1:numel( Q )
x{qi} = fmincon( #(x) Function(x, Q(qi)), A, b );
end
As described in MATLAB documentation, there are actually 3 solutions for this problem:
Anonymous Functions
which is described in the Shai's answer of this post.
Nested Functions:
in this approach the outer function accepts all arguments, and the inner function only accepts parameters that optimization takes place on them.
this is an example taken from MATLAB documentation:
function [x,fval] = runnested(a,b,c,x0)
[x,fval] = fminunc(#nestedfun,x0);
% Nested function that computes the objective function
function y = nestedfun(x)
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)x(2) +...
(-c + cx(2)^2)*x(2)^2;
end
end
Global Variables
in this approach you should define the parameters that are needed in objective function as global in workspace, and use them in objective function with declaring them as global.
here is an example again from MATLAB documentation:
Defining objective function:
function y = globalfun(x)
global a b c
y = (a - b*x(1)^2 + x(1)^4/3)*x(1)^2 + x(1)x(2) + ...
(-c + cx(2)^2)*x(2)^2;
end
Optimization:
global a b c;
a = 4; b = 2.1; c = 4; % Assign parameter values
x0 = [0.5,0.5];
[x,fval] = fminunc(#globalfun,x0)
You may be able to do the following:
x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options,Q)
which will pass Q along to fun(x,Q)!