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
CodePudding user response:
You can update the XData
and YData
properties of a single line instead of creating a new one.
I've added comments to the below code to explain the edits
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
CodePudding user response:
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