Using ode45, how can I help ode45 keep track of a calculated value in my ODEFUN function while not treating it as a derivative?
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
Steven Lord
on 24 Mar 2023
How would you handle the scenario where the "previous" time step was actually later than the current time step? If the solver tries too large a step and cannot satisfy the tolerances you've specified it can reject the step and try a smaller one. So that "previous" time step when t = 1 could in fact be from t = 1.25 as an example.
If the mathematical form of your differential equation(s) you're solving involves a delay you don't have an ordinary differential equation (ODE) you have a delay differential equation (DDE) and you should use dde23 or similar functions to solve it rather than ode45.
If not, show us the mathematical form of the problem you're trying to solve and we may be able to offer suggestions.
Answers (1)
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
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!