MATLAB: How to hold the second to last image of the simulation

Image Processing Toolboxkeep image

hold on
axis equal
axis off
b = 0:pi/40:pi/4;
c = 0:pi/20:pi/2;
P4vct=nan(numel(b),2);
for k = 1:numel(b)
P1=[-15,0];
P2=[-5,0];
plot([P1(1) P2(1)],[P1(2) P2(2)],'LineWidth',5,'Color','black');
A=[0,0];
h{1} = viscircles(A,5,'LineWidth',2,'Color','black');
B = A+[10*cos(b(k)-pi/4),10*sin(b(k)-pi/4)];
h{2} = viscircles(B,5,'LineWidth',2,'Color','green');
C = B+[10*cos(c(k)-pi/2),10*sin(c(k)-pi/2)];
h{3} = viscircles(C,5,'LineWidth',2,'Color','blue');
P3=C+[5*cos(c(k)-(pi/2)),5*sin(c(k)-(pi/2))];
P4=C+[15*cos(c(k)-(pi/2)),15*sin(c(k)-(pi/2))];
h{4} = plot([P3(1) P4(1)],[P3(2) P4(2)],'LineWidth',5,'Color','black');
P4vct(k,:) = P4;
h{5} = plot(P4vct(:,1),P4vct(:,2), '--','LineWidth',3,'Color','blue');
drawnow();
pause(0.5);
delete(vertcat(h{1:4}));
end
hold off
axis equal
axis off

Best Answer

At the bottom of the loop, only call delete() if it's not the last one:
if k < numel(b)
delete(vertcat(h{1:4}));
end
0000 Screenshot.png