Creating a point moving along a chart in MATLAB

I want to create a simple log (x) graph in MATLAB, in which the model shows a point moving along a curve over time.

The overall goal is to have two of these graphs next to each other and apply an algorithm to them. I'm really not sure where to start here.

I am relatively new to MATLAB coding, so any help would be very helpful!

Thanks Luke

+3
source share
5 answers

Here is a variant of @Jacob . Instead of redrawing everything in each frame ( clf), we simply update the location of the point:

%# control animation speed
DELAY = 0.01;
numPoints = 600;

%# create data
x = linspace(0,10,numPoints);
y = log(x);

%# plot graph
figure('DoubleBuffer','on')                  %# no flickering
plot(x,y, 'LineWidth',2), grid on
xlabel('x'), ylabel('y'), title('y = log(x)')

%# create moving point + coords text
hLine = line('XData',x(1), 'YData',y(1), 'Color','r', ...
    'Marker','o', 'MarkerSize',6, 'LineWidth',2);
hTxt = text(x(1), y(1), sprintf('(%.3f,%.3f)',x(1),y(1)), ...
    'Color',[0.2 0.2 0.2], 'FontSize',8, ...
    'HorizontalAlignment','left', 'VerticalAlignment','top');

%# infinite loop
i = 1;                                       %# index
while true      
    %# update point & text
    set(hLine, 'XData',x(i), 'YData',y(i))   
    set(hTxt, 'Position',[x(i) y(i)], ...
        'String',sprintf('(%.3f,%.3f)',[x(i) y(i)]))        
    drawnow                                  %# force refresh
    %#pause(DELAY)                           %# slow down animation

    i = rem(i+1,numPoints)+1;                %# circular increment
    if ~ishandle(hLine), break; end          %# in case you close the figure
end

enter image description here

+7
source

, COMET, .

( , @Jacob)

x = 1:100;
y = log(x);
comet(x,y)

( "" ),

x = 1:100;
y = log(x);
plot(x,y,'r')
hold on %# to keep the previous plot
comet(x,y,0) %# 0 hides the green tail
+2

A simple solution:

x = 1:100;
y = log(x);
DELAY = 0.05;
for i = 1:numel(x)
    clf;
    plot(x,y);
    hold on;
    plot(x(i),y(i),'r*');
    pause(DELAY);
end
+2
source

slightly more complicated solution on the same lines as @Jacob. Here I add some optimization using manual graphics and a MATLAB movie object for playback.

x=1:100;
y=log(x);
figure
plot(x,y);
hold on; % hold on so that the figure is not cleared
h=plot(x(1),y(1),'r*'); % plot the first point
DELAY=.05;


for i=1:length(x)
    set(h,'xdata',x(i),'ydata',y(i)); % move the point using set
                                      % to change the cooridinates.
    M(i)=getframe(gcf);
    pause(DELAY)
end

%% Play the movie back

% create figure and axes for playback
figure
hh=axes;
set(hh,'units','normalized','pos',[0 0 1 1]); 
axis off

movie(M) % play the movie created in the first part
0
source

solution could be that way

x = .01:.01:3;
comet(x,log(x))
0
source

Source: https://habr.com/ru/post/1791258/


All Articles