MATLAB: Do I receive an invalid object handle after plotting when using MATLAB

claMATLAB

I use the FINDOBJ function to locate an axes object. Whenever I plot inside this axes, I can no longer use FINDOBJ:
axes('Tag','plotting area')
h = findobj('Tag','plotting area');
axes(h)
plot(1:10)
clear h
h = findobj('Tag','plotting area');
axes(h)
??? Error using ==> axes
Invalid object handle.

Best Answer

In order for the "tag" property and other axes properties to be preserved after plotting, the value of the "NextPlot" property for the axes that you are using must be changed.
The "NextPlot" property has 3 possible values:
add -- use the existing axes to draw graphics objects.
replace -- reset all axes properties except "position" to their defaults and delete all axes children before displaying graphics
replacechildren -- remove all child objects, but do not reset axes properties
The default setting is "replace." Therefore, a call to the PLOT function will reset the "tag" property to an empty string and FINDOBJ will not be able to obtain a handle to this object. Typing "hold on" at the command prompt changes the value of the "NextPlot" property of the current axes to "add". Alternatively, add the following line of code prior to calling PLOT in order to prevent the "Invalid object handle" error message:
set(gca,'NextPlot','add')
For more information on the "NextPlot" property of the axes object, refer the following documentation:
<http://www.mathworks.com/access/helpdesk/help/techdoc/ref/axes_props.html#NextPlot>