I usually use a pattern like this, which is also used by many of the plotting functions that are part of MATLAB:
function varargout = myplot(obj, varargin)
% Check the number of output arguments.
nargoutchk(0,1);
% Parse possible axes input.
[ax, args, ~] = axescheck(varargin{:}); %#ok<ASGLU>
% Get handle to either the requested or a new axis.
if isempty(ax)
hax = gca;
else
hax = ax;
end
% At this point, hax refers either to a specified axis, or
% to a fresh one if none was specified. args refers to the
% remainder of any arguments passed in varargin.
% Parse the rest of args
% Make the plot in hax
% Output a handle to the axes if requested.
if nargout == 1
varargout{1} = hax;
end
end
axescheck is an undocumented function. You're always taking a small risk by doing that, but it's been present and unchanged in MATLAB since forever, and it's used by many very stable plotting functions within MATLAB, so you should be OK.
What it does is to check whether the first argument is a handle to an axis. If it is, then ax is that handle, and args is the rest of the input arguments. If not, then ax is empty and args contains all of the input arguments.
Hope that helps!
Edit: More information about axescheck as requested.
Firstly, you can see the location and source code for axescheck by typing which axescheck and edit axescheck. In this way you can see exactly what it does.
The syntax is [AX, ARGS, NARGS] = AXESCHECK(ARG1, ARG2, ...).
Firstly, it checks if ARG1 is a handle to an axis. If so, it's returned as AX, the remaining arguments (ARG2, ...) are returned in ARGS, and NARGS is the value of nargin minus 1.
Secondly, it checks if any of the input arguments is a parameter-value pair with parameter Parent. If so, then all parameter-value pairs with the parameter Parent are removed from the list. The specified axis is returned in AX, the remaining arguments are returned in ARGS, and NARGS is the value of nargin minus the number of removed arguments.
If no axis is specified in either of the above ways, then AX is empty, ARGS is just the input arguments, and NARGS is the value of nargin.
axescheck works with either old-style (Handle Graphics 1) double handles, and new-style (Handle Graphics 2) handles of the class matlab.graphics.axis.Axes.
It also checks whether the supplied handle is a handle to a deleted object, throwing an error if it is.
It's quite widely used within many built-in MATLAB plotting functions - see, for example, hist.m, polar.m, surfl.m, bar3.m, comet.m, pie.m and many others.