Trouble deleting plots with circle animation
2 views (last 30 days)
Show older comments
Hello everyone,
I want to make a smooth animation of a circle that grows and shrinks according to an (eventually large) vector of radiuses. I have tried to make a function for this, shown below. To display all circles with different radiuses in one figure is no problem, but I can’t figure out how to delete the previous circle. I have tried the delete(h) command in a couple different places, but that didn’t help. If I remove the hold on and hold off command, than only the current circle is plotted, but the axis jumps all over the place.
If you have any insights, let me know!
M = [3 4 6 5 8 9];
axis([-15 15 -15 15])
axis square
circle(M)
function h = circle(M)
for i = 1:length(M)
hold on
a = 0:pi/50:2*pi;
x = M(i) * cos(a);
y = M(i) * sin(a);
h = plot(x, y, "LineWidth", 4);
pause(0.1)
hold off
end
end
0 Comments
Accepted Answer
Adam Danz
on 18 Sep 2023
Edited: Adam Danz
on 19 Sep 2023
Based on the code, I think you want to delete the previous circle here (marked by a comment below).
M = [3 4 6 5 8 9];
axis([-15 15 -15 15])
axis square
hold on
circle(M);
hold off
function h = circle(M)
for i = 1:length(M)
a = 0:pi/50:2*pi;
x = M(i) * cos(a);
y = M(i) * sin(a);
h = plot(x, y, "LineWidth", 4);
pause(0.1)
delete(h) %<---- Try this
end
end
However, this approach would be more efficient.
Instead of deleting and replacing the circle, you can update it's x and y values. Unlike the previous version, this will not change the color of the circle but you could update that as well.
M = [3 4 6 5 8 9];
axis([-15 15 -15 15])
axis square
circle(M);
function h = circle(M)
h = plot(nan,nan,'LineWidth',4); % <- initialize the graphics object
for i = 1:length(M)
a = 0:pi/50:2*pi;
x = M(i) * cos(a);
y = M(i) * sin(a);
set(h,'XData',x,'YData',y) % <---- update x,y
pause(0.1)
end
end
2 Comments
Adam Danz
on 19 Sep 2023
axis([-15 15 -15 15])
axis square
hold on
box on
a = 0:pi/50:2*pi;
plot(cos(a),sin(a))
More Answers (0)
See Also
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!