MATLAB Answers

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

조회 수: 3(최근 30일)
Peter B.
Peter B. 2021년 8월 3일
댓글: Rik 2021년 8월 4일
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)
axis([0 2*pi -1.5 1.5])
grid on
if k < length(t)
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');
if k < length(t)
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,

채택된 답변

Adam Danz
Adam Danz 2021년 8월 3일
편집: Adam Danz 2021년 8월 3일
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)
  댓글 수: 6
Rik 2021년 8월 4일
No problem, you're not the first, and you won't be the last.

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

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

Start Hunting!

Translated by