# How to save local variables (which are within a called function)

2 ビュー (過去 30 日間)
Ilias Bouchkira 2021 年 8 月 18 日

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 件のコメント表示非表示 なし
Wan Ji 2021 年 8 月 18 日
What are the vraiables you would like to see and save?

サインインしてコメントする。

### 回答 (2 件)

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
%
% 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 件のコメント表示非表示 -1 件の古いコメント

サインインしてコメントする。

Stephen 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])
t = 10×1
0 1 2 3 4 5 6 7 8 9
y = 10×2
2.0000 0 1.5081 -0.7803 0.3231 -1.8334 -1.8699 -1.0310 -1.7461 0.6240 -0.8443 1.3007 1.2669 2.4471 1.9322 -0.4298 1.2329 -0.9745 -0.3645 -2.4967
[~,tmp] = cellfun(@fun,num2cell(t),num2cell(y,2),'uni',0); % or use a loop.
I = cell2mat(tmp)
I = 10×1
-2.0000 -0.5137 -1.9651 4.4439 0.4675 1.2178 -2.7478 -0.7574 -0.7261 -1.8004
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

サインインしてコメントする。

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!