how to let a "plot" immune on any later " hold off" once this "plot" is created.
2 views (last 30 days)
Show older comments
I am a Matlab fan.
pls review my Matlab script file below:
clear;clc;
r=10;
plot([-35,35], [0,0], 'r-.' )
axis equal
hold on
for h=linspace(0,10,10)
theta=linspace(0,2*pi);
x=r*cos(theta);
y=30+h+r*sin(theta);
plot(x,y);
xlim([-50,50]);
ylim([-50,50]);
pause(0.1)
end
if I don't add " hold off" in the " for-end" statement, then the circle creates many ones when it is moving.
if I do add " hold off" in the " for-end" statement, then the horizontal red line is disappeared.
I expect :
1) the horizontal red line is kept once it is ploted before the the " for-end" statement.
2) only one circle is occuring when it is moving.
may you give me a guide?
Thanks in advance!
0 Comments
Accepted Answer
DGM
on 7 Apr 2024
Edited: DGM
on 7 Apr 2024
Here's one idea.
r=10;
plot([-35,35], [0,0], 'r-.' )
axis equal
hold on
% just create a dummy plot object to be used in the loop
hp = plot(0,0);
for h=linspace(0,10,10)
theta=linspace(0,2*pi);
x=r*cos(theta);
y=30+h+r*sin(theta);
% update the plot object with xy data
hp.XData = x;
hp.YData = y;
xlim([-50,50]);
ylim([-50,50]);
pause(0.1)
end
There are other ways. I'd try to pull more stuff outside the loop.
% these don't need to be inside the loop
r = 10;
h = linspace(0,10,10);
theta = linspace(0,2*pi);
plot([-35,35], [0,0], 'r-.' )
axis equal
hold on
% these probably don't need to be inside the loop either
xlim([-50,50]);
ylim([-50,50]);
for k = 1:numel(h)
x = r*cos(theta);
y = 30 + h(k) + r*sin(theta);
if k == 1
% create a new plot object on the first iteration
hp = plot(x,y);
else
% update the plot object with xy data on subsequent passes
hp.XData = x;
hp.YData = y;
end
pause(0.1)
end
4 Comments
DGM
on 17 May 2024
I'm not sure what you're asking for.
If you want to create a bunch of handles to graphics objects, use an array, and not numbered variables like that. You can use gobjects() to preallocate an array which can be populated with handles inside a loop of some sort.
In the given example, there are only ever two line objects: the dashed line and the circle. The second object simply gets its properties updated, so there isn't a new handle to store.
It's possible you intend to capture the axes/figure as a raster image and store those -- for example, to output as an animated GIF or something. For example:
More Answers (0)
See Also
Categories
Find more on Annotations 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!