Using ode45, how can I help ode45 keep track of a calculated value in my ODEFUN function while not treating it as a derivative?
7 views (last 30 days)
Show older comments
function derivs = ODEFUN(time, vars)
derivs(1) = vars(2);
% vars(3) contains variableOfInterest for the PREVIOUS timestep
derivs(2) = vars(3) * 2 + vars(1) / 2;
variableOfInterest = derivs(1) * derivs(2);
end
I want to keep track of a certain variable of interest within my code. variableOfInterest is a calculated value depending on derivs(1) and derivs(2), where derivs(2) depends on the calculated variableOfInterest from the previous timestep. I am doing this because variableOfInterest has no elementary derivative within the context of my project.
I am able to calculate variableOfInterest at the current timestep, but I don't want ode45 to approximate any values pertaining to this variable of interest; however, I still want the previously calculated variableOfInterest to be passed into ODEFUN to continue the approximation. Preferably within vars(3); however, I would be fine with any possible way to access it.
For reference, my original script looks something like this
[time, solution] = ode45(@ODEFUN, timeDiscretized, [xInit, yInit, variableOfInterestInit]);
3 Comments
Answers (1)
Cris LaPierre
on 24 Mar 2023
I think you can just add it to your derivative vector. The only thing that treats it as a derivative is how you use it.
Here is an example that solves a 2nd order ODE (so and ). I've added a 3rd element to y that is the sum of the first 2. If element 3 contains the values I intended, then subtraciting columns 1 and 2 from column 3 should be zeor.
w = 10;
xi = 1;
y0 = [0 0 0]; % Initial conditions
tspan = [0 5];
[t,y] = ode45(@(t,y) ODEFUN(t,y,w,xi),tspan,y0);
sum(y(:,3)-y(:,1)-y(:,2))
function dydt = ODEFUN(time, y, w, xi)
ddt = y(2);
d2dt = 1 - xi*ddt - w^2*y(1);
voi = ddt + d2dt;
dydt = [ddt; d2dt; voi];
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!