Animated data-tip or xline?

Hello,
I am looking to create an animation of a datatip or a vertical line moving across a plot which has arleady been made. I need to be able to control the framerate of the animation (or, the rate at which the line/datatip moves from one x-value to the next). I then (ideally) need to be able to export this animation as a movie. I've checked the documentation for this and it does not seem intuitive at all. If anyone could provide any assistance, it would be much appreciated!
Here is my attempt so far at making a vertical line move across a simple plot at a rate of 4 frames/second:
x=[1:20]
y=sin(x)
L = xline(0)
a=tic
for i = 1:length(x)
delete(L)
L = xline(i)
b = toc(a)
if b>1/4
drawnow
a=tic
end
end
As you probably guessed, it does not work as intended at all. The example code I drew from is here, under "control animation speed."
Any help is much appreciated!

 Accepted Answer

Rather than deleting and recreating the line, just update its properties.
x = 0:360;
y = sind(x);
plot(x, y);
h = xline(x(1));
for k = 2:numel(x)
h.Value = x(k);
pause(0.25);
end
For a few more bells and whistles and to speed it up a little:
x = 0:360;
y = sind(x);
% Only show one marker, at the x value where the xline is located
s = plot(x, y, 'o-', 'MarkerIndices', 1);
h = xline(x(1));
% Use the title to show where the xline is located
t = title("Sine curve with xline at x = " + x(1));
for k = 2:numel(x)
h.Value = x(k);
% 'move' the marker along the sine curve
s.MarkerIndices = k;
% Update the title string
t.String = "Sine curve with xline at x = " + x(k);
% Let's go a little faster
pause(1/36);
end

3 Comments

Thanks so much this works perfectly! I actually needed to use it on a saved figure with nothing in the workspace, so I just used the first code and set x = [start:end] and it worked like a charm! Thanks again.
To take it one step further, any idea how I could save this video as a movie? I've tried messing with the following, but the video doesn't render at all:
v = VideoWriter('274-305.avi');
open(v);
x = [274:305]
h = xline(x(1));
for k = 2:numel(x)
h.Value = x(k);
pause(0.5);
frame=getframe(gcf);
end
writeVideo(v,frame);
Write the frame to the video inside the loop rather than after, as shown in the "Create AVI File from Animation" example on the documentation page for writeVideo.
You probably don't need the pause inside the loop if you set the FrameRate property of the VideoWriter first. Instead you might want to use drawnow instead to make sure MATLAB updates the graphic.

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!