Main Content

Delete Graphics Objects

How to Delete Graphics Objects

Remove graphics objects with the delete function. Pass the object handle as an argument to delete. For example, delete the current axes, and all the objects contained in the axes, with the statement.


If you want to delete multiple objects, pass an array of handles to delete. For example, if h1, h2, and h3 are handles to graphics objects that you want to delete, concatenate the handles into a single array.

h = [h1,h2,h3];

Closing a figure deletes all the objects contained in the figure. For example, create a bar graph.

f = figure;
y = rand(1,5);

The figure now contains axes and bar objects.

ax = f.Children;
b = ax.Children;

Close the figure:


MATLAB® deletes each object.

f = 

  handle to deleted Figure
ax = 

  handle to deleted Axes
b = 

  handle to deleted Bar

Handles to Deleted Objects

When you delete a graphics object, MATLAB does not delete the variable that contains the object handle. However, the variable becomes an invalid handle because the object it referred to no longer exists.

You can delete graphics objects explicitly using the delete function or by closing the figure that contains the graphics objects. For example, create a bar graph.

f = figure;
y = rand(1,5);
b = bar(y);

Close the figure containing the bar graph.


The handle variables still exist after closing the figure, but the graphics objects no longer exist.

  Name      Size            Bytes  Class                           

  f         1x1               104  matlab.ui.Figure                   
  b         1x1               104 
  y         1x5                40  double 

Use isgraphics to determine the validity of a graphics object handle.

ans =


You cannot access properties with the invalid handle variable.

Invalid or deleted object.

To remove the variable, use the clear function.

clear h

See Also

Related Topics