8

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.

Spacey
  • 2,941
  • 10
  • 47
  • 63

3 Answers3

9

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);
groovingandi
  • 1,986
  • 14
  • 16
  • AH! This is nice. It seems to be working for me here. One last thing, I am making a handle h1 here. Is there a way for it to just 'get' the handle from a figure *number* that I know before hand? For example, suppose I made a figure, "figure(9)". Now I want to use this technique on figure(9) only. How to tell it to use figure 9 only? – Spacey Jul 10 '12 at 18:22
  • @Learnaholic: Just look at @Ben's answer, he shows you how to get the list of handles for a certain axes. If you plotted in figure(9), you can set your current figure to figure(9) by executing `figure(9)` again, then use `gca` or `gcf` to get the list of children handles. – groovingandi Jul 10 '12 at 18:26
8

Try

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

(or maybe delete(items(1)))

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
3

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);
sfstewman
  • 5,589
  • 1
  • 19
  • 26
  • 1
    `findobj` would suffice here (FINDALL does extra work to find hidden handles as well) – Amro Jul 11 '12 at 16:45