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

3

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

总体目标是在两个图表并排显示,并对它们应用算法。我不确定从何处开始。

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

谢谢 卢克

5个回答

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


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

+1 我不知道有关彗星的事情。顺便说一下,如果彗星似乎没有作用,请尝试使用更多的点(例如x = 1:.01:100;)。 - Azim J

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

这不是一个好的解决方案,因为每次清除整个图形并且重新绘制所有东西都会非常影响速度和扩展空间等方面。 - mike

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

0

解决方案可以这样

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

Ben请更加详细地描述。 - Christos
这并没有添加任何新的内容,因为 Jonas 的回答已经涵盖了所有内容。 - gnovice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接