Here's one way you could animate this, using the function POLYFIT to fit a parabola to x
and y
, the function POLYVAL to evaluate your polynomial at a set of x
values, and the SET command to modify your plot objects instead of having to replot them:
load objects.mat %# Load the data
x = objects(:,1); %# Get the x data
y = objects(:,2); %# Get the y data
N = numel(x); %# The number of points
hPoints = plot(x(1),y(1),'r*'); %# Plot first point as a red asterisk,
%# saving the handle
hold on; %# Add to the plot
hFitLine = plot(x,nan(N,1),'b-'); %# Initialize the plot for the fit line,
%# saving the handle and using NaN for
%# the y values so it doesn't appear yet
axis([min(x) max(x) min(y) max(y)]); %# Set the axis limits
for k = 1:N
set(hPoints,'XData',x(1:k),'YData',y(1:k)); %# Update the points
if k >= 15 %# Plot a fit line starting at k = 15
p = polyfit(x(1:k),y(1:k),2); %# Fit a parabola with points 1 through k
yFit = polyval(p,x); %# Evaluate the polynomial at all x
set(hFitLine,'YData',yFit); %# Update the fit line
end
drawnow(); %# Force the plot to refresh
pause(0.25); %# Pause for a quarter second
end
A note on MATLAB graphics...
Any time a plotting command is issued (like PLOT), then one or more handle graphics objects are created in the current axes. These objects have a "handle", or a numeric identifier, that acts as a reference to the plot object and which can be used to access and modify the properties of the object. The GET and SET commands can be used to access and modify, respectively, the properties of graphics objects using their handles, which are typically returned as output arguments from the plot commands.
Each type of handle graphics object has a set of properties. The PLOT command creates a lineseries
object with a number of properties which can be found here. For example, the 'XData'
property stores the x values of the plotted points, while the 'YData'
property stores the y values. You can change the x and y positions of the plotted points by modifying these properties of the lineseries
object.
When animating graphics in MATLAB, it is generally more efficient to create the object first and update its properties during the animation instead of creating, deleting, then recreating the object during the animation. In the code above, a plot object for the individual points is created before the animation loop and the handle for that object is stored in the variable hPoints
. A plot object for the parabolic line is also created before the animation loop, and its handle is stored in hFitLine
. Then, the SET command is used in the loop to modify these two plot objects.
Since the parabolic line is intended to be invisible at first, setting the initial y values to be all NaN causes the line to not be rendered (although the object still exists). You could also make the line invisible by setting its 'Visible'
property to 'off'
.