Interactive animation while solving ODE

3 次查看(过去 30 天)
I am using ode45 to solve a system representing the inverted pendulum and its control. I am using the solution to plot the system in the form of an animation using the position x and the angle of the pendulum ϕ.
I would like to add new functionalities to this simulation, such as an external disturbance. I have been able to successfully code this functionality by changing the code, but it is static, i.e. I need to define the disturbance before calling ode45. Is there a way to solve / integrate this system in real time? I mean, I'd like to keep solving the system continuously, without defining a time range previously. This way, the user might disturb the system whenever he wants and the system will respond accordingly.

采纳的回答

Jan
Jan 2018-12-28
You can use the event function to trigger an external event:
Opt = odeset('Events', @yourEvent);
t0 = 0;
tEnd = 1000;
y0 = [0,0];
Param = 17;
while t0 < tEnd
yourFcn = @(t,y) yourFcn(t, y, Param);
[time, pos] = ode45(yourFcn, [t0, tEnd], y0, Opt);
t0 = time(end);
y0 = pos(end, :);
Param = ??? % Adjust the parameter like you want.
end
And your event function:
function [value, isterminal, direction] = yourEvent(t, y)
persistent P
if nargin == 0
P = 1;
return;
end
drawnow;
if isempty(P)
value = 0;
isterminal = 0;
direction = 0;
else
value = -1;
isterminal = 1;
direction = 0;
P = [];
end
end
Now ODE45 calls yourEvent with 2 inputs every time. But you can call this function from a timer callback also without input arguments. Then the persistent variable P is used as a flag, which stops the integration in the next time step. This allows the main loop while t0<tEnd to modify the parameters used inside the function to be integrated, or maybe the current velocities or positions.
The drawnow is important, because without it, Matlab does not evaluate the other callbacks.
  2 个评论
Ankith Anil Das
Ankith Anil Das 2020-1-31
Hi!
Would it be possibe to show me an example with such an eventFunction implementation. Also, what do you mean by "timer callback also without input arguments" and how do you set it up with events function ?
Thank you so much
Jan
Jan 2020-2-2
The posted code contains such an example already.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by