Search code examples
matlabplotmatlab-figure

Dynamic plot in each iteration in MATLAB


In the following code, plot(plot_x,plot_y,'-k'); in current iteration shows the previous iterations plots.

But I want to show only the current iteration plot, i.e., previous plot should be disappeared. However, plot(N_x,N_y,'Ob','MarkerSize',10); should be there always. What kind of modification should I do?

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

Solution

  • In the plot loop, ask the plot function returnig the handle of the line, then, after the pause statement delete the line by calling the delete function.

    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