How to save local variables (which are within a called function)
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Dear all,
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
tspan=[0:1];
initial_moments=[20,2.4e-12,3e-12,1.2737e-13];
[tsol,moments]=ode15s(@ODE_System,tspan,initial_moments);
1 comentario
Respuestas (2)
Ive J
el 18 de Ag. de 2021
Editada: Ive J
el 18 de Ag. de 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
then
[t,y] = ode45(@vdp1,[0 20],[2; 0]);
0 comentarios
Stephen23
el 18 de Ag. de 2021
Editada: Stephen23
el 18 de Ag. de 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];
end
0 comentarios
Ver también
Categorías
Más información sobre Ordinary Differential Equations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!