Spacey
Spacey

Reputation: 3017

In MATLAB, how does one clear the last thing plotted to a figure?

In MATLAB, I plot many different vectors to a figure. Now, what I would like to do is simply undo the last vector that I plotted to that figure, without clearing everything else. How can this be accomplished? Can it be accomplished?

Thanks

Edit:

figure(1); clf(1);
N = 100;
x = randn(1,N);
y = randn(1,N);
z = sin(1:N);
plot(x); hold on;
plot(y,'r');
plot(z,'k'); 

Now here, I would like to remove the plot z, which was the last plot I made.

Upvotes: 8

Views: 27711

Answers (3)

sfstewman
sfstewman

Reputation: 5677

The answer that @groovingandi gives is the best way to generally do it. You can also use FINDALL to find the handle based on the properties of the object:

h = findall(gca, 'type', 'line', 'color', 'k');
delete(h);

This searches the current axes for all line objects (plot produces line objects) that are colored black.

To do this on, say, figure 9, you need to find the axes for figure 9. Figure handles are simply the figure number, so:

ax = findall(9, 'axes');
h = findall(ax, 'type', 'line', 'color', 'k');
delete(h);

Upvotes: 3

Ben Voigt
Ben Voigt

Reputation: 283614

Try

items = get(gca, 'Children');
delete(items(end));

(or maybe delete(items(1)))

Upvotes: 10

groovingandi
groovingandi

Reputation: 2006

If you know before plotting that you want to remove it again later, you can save the handle returned by plot and delete it afterwards.

figure;
h1 = plot([0 1 2], [3 4 5]);
delete(h1);

Upvotes: 9

Related Questions