How to save local variables (which are within a called function)
8 views (last 30 days)
I'm using the script bellow to solve a ode, however, there are some variables (calculated inside the function @ODE_System) and i would like to see and save their values along with the solutions ;
is there any way to do this, thank you so much in advance;
% This is the script to solve the model using ODE15s
Ive J on 18 Aug 2021
Edited: Ive J on 18 Aug 2021
I don't know what's the use of doing this. But given what you need, you can do something like this:
function dydt = vdp1(t,y)
%VDP1 Evaluate the van der Pol ODEs for mu = 1
% See also ODE113, ODE23, ODE45.
% Jacek Kierzenka and Lawrence F. Shampine
% Copyright 1984-2014 The MathWorks, Inc.
dydt = [y(2); (1-y(1)^2)*y(2)-y(1)];
save("t"+string(t)+".mat", 'dydt') % add required variables to be saved
[t,y] = ode45(@vdp1,[0 20],[2; 0]);
Stephen23 on 18 Aug 2021
Edited: Stephen23 on 18 Aug 2021
"...there are some variables (calculated inside the function @ODE_System) and i would like to see and save their values along with the solutions ; is there any way to do this"
There are ways to do this, but they are unlikely to be very helpful for you because only some calls of the function correspond to solutions returned by the ODE solver. This is because ODE solvers can change the step size arbitrarily, can even make steps backwards, and not all function calls correspond to output values. So if you simply save every value calculated on every function call, it is not a trivial task to work out which of them actually correspond to valid solutions values returned by the ODE solver. I would not recommend that approach.
Unless solving your ODE function is extremely slow (on the order of hours/days) then by far the simplest approach is to first solve the ODE and then call the function with the solution values to get the intermediate values.
Here is a working example:
[t,y] = ode45(@fun,0:9,[2;0])
[~,tmp] = cellfun(@fun,num2cell(t),num2cell(y,2),'uni',0); % or use a loop.
I = cell2mat(tmp)
function [dydt,intv] = fun(t,y) % all required intermediate values as outputs.
intv = (1-y(1)^2)*y(2)-y(1);
dydt = [y(2);intv];