MATLAB: Alternatives to “drawnow”

MATLABplotting

Hi!
I'm trying to plot a moving graph, using the "drawnow" function. Nevertheless, I am wondering whether it is possible to control the plotting pace.
I'm using "pause" function, but there also are instabilities. Is there an alternative to avoid them?
Furthermore, I'd like to know if there's a way to stop the plotting process (besides from the pause button).
My code is:
clear
clc
close
t3=linspace(0, 500, 2000);
x2=linspace(0, 10, 100);
%for n=1:leng
for i=1:length(t3)
y2=3*sin(0.5*x2-0.1*t3(i)-0.3);
plot(x2, y2)
%xlabel('x(m)','FontSize',15)
%ylabel('y(t, x) (m)','FontSize',15)
drawnow
pause(0.01)
end
Thank you!!

Best Answer

It looks like your x data never changes. That should mean your number of y points also remains constant. One thing to try is to just update the YData rather than creating a new plot.
As for how to stop it manually, you could attach a callback to your figure to detect either a key press or a click in an empty part of the figure window. You can read more about the available callbacks here.
t3=linspace(0, 500, 2000);
x2=linspace(0, 10, 100);
y2=3*sin(0.5*x2-0.1*t3(1)-0.3);
stopAnimation=0;
fig = figure('Visible',"on",...
'KeyPressFcn',@keyPress, ...
'ButtonDownFcn',@buttonPress)
h = plot(x2, y2);
xlabel('x(m)','FontSize',15)
ylabel('y(t, x) (m)','FontSize',15)
for i=2:length(t3)
if stopAnimation
break
end
y2=3*sin(0.5*x2-0.1*t3(i)-0.3);
h.YData = y2;
drawnow limitrate
pause(0.01)
end
function keyPress(H,E)
assignin('base','a',1)
end
function buttonPress(H,E)
assignin('base','a',1)
end