在MATLAB中创建沿图形移动的点

时间:2011-02-10 16:06:49

标签: matlab animation graph model plot

我希望在MATLAB中创建一个简单的 log(x)图,其中模型显示随时间沿曲线移动的点。

总体目标是将这些图表中的两个并排放置并对其应用算法。我真的不确定从哪里开始。

我在MATLAB编码方面相对较新,所以任何帮助都非常有用!

由于 路加

5 个答案:

答案 0 :(得分:7)

以下是@Jacob解决方案的变体。我们只需更新点的位置,而不是重新绘制每个帧的所有内容(clf):

%# 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

答案 1 :(得分:2)

您可能需要查看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 :(得分:2)

一个简单的解决方案是:

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

答案 3 :(得分:0)

与@Jacob一样的更复杂的解决方案。在这里,我使用句柄图形和MATLAB电影对象添加一些优化进行播放。

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

答案 4 :(得分:0)

解决方案可以这样

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