MATLAB 每次迭代中的动态绘图

Dynamic plot in each iteration in MATLAB

在以下代码中,当前迭代中的 plot(plot_x,plot_y,'-k'); 显示了之前的迭代图。

但我只想显示当前的迭代图,即之前的图应该消失。但是,plot(N_x,N_y,'Ob','MarkerSize',10); 应该始终存在。我应该做什么样的修改?

N = 50;
L = 20;
itr = 5;
N_x = (rand(N,1)-0.5)*L;
N_y = (rand(N,1)-0.5)*L;
plot(N_x,N_y,'Ob','MarkerSize',10);
grid on;
hold on;
axis([-0.5*L 0.5*L -0.5*L 0.5*L]);
for n = 1:itr
    out = randperm(N,5);
    plot_x = N_x(out);
    plot_y = N_y(out);
    plot(plot_x,plot_y,'-k');
    hold on;
    pause(1);
end

您可以更新单行的 XDataYData 属性,而不是创建新行。

我已经在下面的代码中添加了注释来解释所做的修改

N = 50;
L = 20;
itr = 5;
N_x = (rand(N,1)-0.5)*L;
N_y = (rand(N,1)-0.5)*L;
plot(N_x,N_y,'Ob','MarkerSize',10);
grid on;
hold on;
axis([-0.5*L 0.5*L -0.5*L 0.5*L]);
p = plot(NaN, NaN, '-k'); % Create a dummy line to populate in the loop
for n = 1:itr
    out = randperm(N,5);
    plot_x = N_x(out);
    plot_y = N_y(out);
    set( p, 'XData', plot_x, 'YData', plot_y ); % Update the line data
    drawnow(); % flush the plot buffer to force graphics update
    pause(1);
end

在绘图循环中,要求 plot 函数返回该行的句柄,然后,在 pause 语句之后调用 delete 函数删除该行。

for n = 1:itr
    out = randperm(N,5);
    plot_x = N_x(out);
    plot_y = N_y(out);
    %   
    % Get the handle of the line
    %
    hp=plot(plot_x,plot_y,'-k');
    hold on;
    pause(1);
    %   
    % Delete the line
    %
    delete(hp)
end