Programming: I can not update inside my function

4 views (last 30 days)
Hello everybody. Here is my problem: I have a function which will be called by ODE45 and we know that ODE45 will differentiate it numerically at each time.My problem is that when I calculate my parameters for first time everything is fine but for second time, there is a error that that value does not exist. But I did calculate it during the first time. here is my program summary for more clarification:
function xdot=sys1(t,X,B,DLar,DLbr,DLcr,Rr)
if t==0
xdot=zeros(50,1); % for initializing the program at the beginning
end
w=xdot(49)
theta=xdot(50)
%%theta and w will be used to update my U and A matrix %%
xdot=A*X+B*U;
end
As you see I calculated xdot and now I must have a new value for xdot(49) and xdot(50). but for second time xdot is not recognized.

Accepted Answer

Sean de Wolski
Sean de Wolski on 26 Aug 2014
tdot is not a persistent variable so it will not persist across function calls. It will be cleared out at the end of each iteration when the function exits.
I would recommend making this function a nested function inside of the function that calls ode45. This was the variable will remain across function calls and can update the way you wish. Some documentation to get you started with nested functions is available here:
  3 Comments
Sean de Wolski
Sean de Wolski on 26 Aug 2014
Show the code with the nested function, it should look something like this in structure:
function main
% create some variables
xdot = zeros(50,1);
ode45(@myfun,...)
function yy = myfun(t,y,etc)
xdot %is available for use!
end
end

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!