How to save local variables (which are within a called function)
조회 수: 8 (최근 30일)
이전 댓글 표시
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);
답변 (2개)
Ive J
2021년 8월 18일
편집: Ive J
2021년 8월 18일
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
Stephen23
2021년 8월 18일
편집: Stephen23
2021년 8월 18일
"...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
참고 항목
카테고리
Help Center 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!