How to set an optional function input as a first input?

I am trying to make a function with syntax similar to plot(ax, ...), where the handle to an axis can be included before the required inputs, but is optional. Such as:
function add2plot(ax, x, y, varargin)
Everything I have found forces the required inputs to be first, including inputParser and manual parsing of varargin. So how does plot() do it?? I am using ver. 2013b, where the handle is a double, and thus hard to distinguish from my numerical x input. The addition of varargin makes using nargin complicated.
Any input is appreciated!

 採用された回答

Cedric
Cedric 2015 年 9 月 11 日
編集済み: Cedric 2015 年 9 月 11 日

1 投票

You can pass whatever you want to the parser; it doesn't get automatically what is passed to the function, but works on what you pass to its parse method. You have therefore the freedom to do something like:
function foo( varargin )
% - Extract first optional axes handle. Remove if present.
if ~isempty( varargin ) && ishandle( varargin{1} )
ax = varargin{1} ;
varargin = varargin(2:end) ;
else
ax = [] ;
end
% - Build input parser and parse remaining args.
parser = inputParser ;
parser.StructExpand = true ;
parser.CaseSensitive = false ;
parser.addRequired( .. ) ;
.. etc.
parser.parse( varargin{:} ) ; % Pass only remaining args.
args = parser.Results ;
% - ...
end

4 件のコメント

Jennifer Taylor
Jennifer Taylor 2015 年 9 月 11 日
Perfect, thank you! Somehow ishandle never came up in my search.
Cedric
Cedric 2015 年 9 月 11 日
編集済み: Cedric 2015 年 9 月 11 日
You're welcome! It's a bit confusing, for function handles you'd use isa(f, 'function_handle') instead.
Walter Roberson
Walter Roberson 2015 年 9 月 11 日
From R2014b onwards it is better to use http://www.mathworks.com/help/matlab/ref/isgraphics.html
Cedric
Cedric 2015 年 9 月 12 日
Thank you Walter, I had missed this information. It makes me realize that I should make a synthesis of all releases information since .. a long time ago, and scan/update/refactor a lot of projects!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeArgument Definitions についてさらに検索

製品

質問済み:

2015 年 9 月 11 日

コメント済み:

2015 年 9 月 12 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by