Is there a better way to animate a figure with AppDesigner?

69 views (last 30 days)
Hello everyone,
I wrote a little Code I found on YouTube, which animates a Sine-Wave in a figure. First I calculate the Y-data and save them in "y". Then I use a for-loop with the "pause"-command to plot them over "t". It runs very smooth, as you would expect. Here is the code:
close all, clear all
t = 0:0.1:2*pi;
y = sin(t);
hold on
for k = 1:length(t)
plot(t(1:k),y(1:k))
axis([0 2*pi -1.5 1.5])
grid on
pause(0.0001)
if k < length(t)
clf
end
end
With this way of proceeding I tried the same with a GUI created in AppDesigner. Here is the code an the Window I created:
methods (Access = private)
% Button pushed function: StartButton
function StartButtonPushed(app, event)
t = 0:0.01:2*pi;
y = sin(t);
hold(app.UIAxes, 'on')
for k = 1:length(t)
plot(app.UIAxes, t(1:k),y(1:k), "LineWidth", 2, 'Color', 'b');
pause(0.0001)
if k < length(t)
cla(app.UIAxes);
end
end
end
end
I exported the GUI and it runs okay but not as good as with the .m-file. I allready read, that the AppDesigner does not have such good performance, but I'm not sure if this way of programming the animation is a good one.
Can somebody tell me, if there is a way to animate lines or similar objects with AppDesigner, which will lead to a better performance?
Thank You!
With kind regards,
Peter

Accepted Answer

Adam Danz
Adam Danz on 3 Aug 2021
Edited: Adam Danz on 3 Aug 2021
It looks nice but it's very inefficient. On each iteration you're throwing out everything and rebuilding it from scratch. See these resources for better methods:
Here's an example of the 2nd method in the first link above, applied to your demo.
app.UIAxes = uiaxes();
t = 0:0.1:2*pi;
y = sin(t);
h = plot(app.UIAxes,nan,nan);
hold(app.UIAxes, 'on')
grid(app.UIAxes, 'on')
xlim(app.UIAxes, [0 2*pi])
ylim(app.UIAxes, [-1.5 1.5])
for k = 1:numel(t)
set(h,'XData',t(1:k), 'YData', y(1:k))
drawnow(); pause(0.015)
end
  6 Comments
Peter B.
Peter B. on 4 Aug 2021
Hello Rik,
I never thought that You missspelled Your name. I just wasn't fully attentive. Please excuse me.
Kind regards,
Peter
Rik
Rik on 4 Aug 2021
No problem, you're not the first, and you won't be the last.

Sign in to comment.

More Answers (0)

Categories

Find more on Animation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!