Programming: I can not update inside my function

1 Ansicht (letzte 30 Tage)
Babak
Babak am 26 Aug. 2014
Kommentiert: Babak am 26 Aug. 2014
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.

Akzeptierte Antwort

Sean de Wolski
Sean de Wolski am 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 Kommentare
Sean de Wolski
Sean de Wolski am 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
Babak
Babak am 26 Aug. 2014
Thank you very much

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by