MATLAB Answers

how to ascribe two values to a parameter such that it will be time dependent

4 views (last 30 days)
Andrew Agada
Andrew Agada on 2 Sep 2021
Commented: Fabio Freschi on 2 Sep 2021
In this my attached code i wanted to vary the value of gamma such that it will be dependent on the tspan in the driver.
when tspan is <=7 gamma should be equal to 0.001 as show in the attached code
but when tspan is >7 gamma should be equal to 1.
find attach the code and the driver used for runing the code.

Answers (2)

Fabio Freschi
Fabio Freschi on 2 Sep 2021
You can pass an extra parameter to RiceG1 function using an anonmymous function. In your driver function add
% extra anonimous function to pass tspan
myfun = @(t,y)RiceG1(t,y,tspan);
% call to ode45
[B,V] = ode45(myfun,tspan,y0);
Then modify RiceG1 to accept the extra parameter and make the choice. I write below an extract of the function
function dy = RiceG1(~,y,tspan)
% ...
if tspan(2) <= 7
gamma = 0.001;
gamma = 1;
I have assumed that the check must be done on tspan(2). The modified files are attached.

Walter Roberson
Walter Roberson on 2 Sep 2021
Unfortunately, Fabio's suggestion will not work. When you change the gamma during computation, you introduce a discontinuity in the derivative of the functions being integrated, and the mathematics of ode45 becomes invalid when you have discontinuities like that. You need to stop integrating and start again where you left off, but with the different gamma value.
You should, however, use the technique of passing in an additional parameter -- but it should be gamma directly, not tspan.
y0 = [1200 400 60 30 30 30 30 30 20 10 3000 30000];
tspan1 = [0 7];
tspan2 = [7 15];
gamma1 = 0.001;
gamma2 = 1;
funs = {@RiceG1, @RiceG2, @RiceG3, @RiceG4, @RiceG5};
for K = 1 : length(funs)
[t_out1, y_out1] = ode45(@(t,y)funs{K}(t,y,gamma1), tspan1, y0);
[t_out2, y_out2] = ode45(@(t,y)funs{K}(t,y,gamma2), tspan2, y_out1(end,:));
t_out{K} = [t_out1; t_out2];
y_out{K} = [y_out1; y_out2];
[B, C, D, E, F] = deal(t_out{:});
[V, W, X, Y, Z] = deal(y_out{:});

Sign in to comment.





Community Treasure Hunt

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

Start Hunting!