MATLAB Examples

Trace Marker Along Line

This example shows how to trace a marker along a line by updating the data properties of the marker.

Plot a sine wave and a red marker at the beginning of the line. Set the axis limits mode to manual to avoid recalculating the limits throughout the animation loop.

x = linspace(0,10,1000);
y = sin(x);
hold on
p = plot(x(1),y(1),'o','MarkerFaceColor','red');
hold off
axis manual

Move the marker along the line by updating the XData and YData properties in a loop. Use a docid:matlab_ref.f56-719157 or drawnow limitrate command to display the updates on the screen. drawnow limitrate is fastest, but it might not draw every frame on the screen.

Note: Starting in R2014b, you can use dot notation to set properties. If you are using an earlier release, use the docid:matlab_ref.f67-432995 function instead, such as set(p,'XData',x(k)).

for k = 2:length(x)
    p.XData = x(k);
    p.YData = y(k);

The animation shows the marker moving along the line.