Using drawnow and delete to move a circle on the last point of a line as it's x and y vectors grow

4 views (last 30 days)
I'm trying to learn something simple in Matlab. My ultimate goal is to create a simulation that models planets as they move around each other and are affected by each others orbits
What I want to do is track their path on a 2d plot with a solid line... but display their current position with a circle I tried to create a simple plot to test this
clear
clc
close all
x=[]
y=[]
n=0
z=0
m=0
run1=0
cirshow=[]
while m<2
n=n+1
m=m+.1
x(n)=m
y(n)=x(n)^2
cirshow(n)=plot(x(n),y(n),'bo')
plot(x,y,'b-')
axis([0 3 0 3])
hold on
if run1==1
delete(cirshow(n-1))
end
drawnow
run1=1
end
so my idea with the code here is to hold on two plots... one for the line and one for each coordinate with a circle -and then delete the second to last circle each time with 'delete'
%% Any help on how to fix this... and maybe also how to improve its efficiency would be greatly appreciated.

Accepted Answer

Vasko Nechev
Vasko Nechev on 13 May 2017
Never mind I fixed it! It was all due to a 'hold on' command in the wrong spot I think Learning coding is always like that
here is the fixed code
clear
clc
close all
x=[];
y=[];
n=0;
z=0;
m=0;
run1=0;
cirshow=[];
while m<2
n=n+1;
m=m+.1;
x(n)=m;
y(n)=x(n)^2;
cirshow(n)=plot(x(n),y(n),'bo')
hold on
plot(x,y,'b-')
axis([0 3 0 3]);
if run1==1
delete(cirshow(n-1))
end
drawnow
run1=1;
end

More Answers (1)

Image Analyst
Image Analyst on 12 May 2017
You may want to throw in a pause(0.2) in right before the end of the loop. Change the number to control the speed.
Also, you can compute your x, y, and z all in advance of the loop. And use a for loop instead of a while loop.
  2 Comments
Image Analyst
Image Analyst on 13 May 2017
I would think any timing differences would be insignificant. But you can try it yourself
n = 1000000 % A million iterations
tic;
for k = 1 : n
end
toc
tic
k = 1;
while k <= n
k = k + 1;
end
toc
Elapsed time is 0.001823 seconds.
Elapsed time is 0.002494 seconds.
With a million iterations the difference is only about 0.6 milliseconds or so - not enough to notice. How many iterations do you plan on having?

Sign in to comment.

Categories

Find more on Graphics Performance 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!