Different Function Input Formats

6 ビュー (過去 30 日間)
Samuel Brewton
Samuel Brewton 2021 年 4 月 9 日
コメント済み: Samuel Brewton 2021 年 4 月 9 日
I'm looking for examples or documentation on how to create a function with different input formats.
An example would be how, using the plot command, you can use it as plot(x,y) or you could put in plot(x,y,'bo','MarkerFaceColor','b') if you wanted solid blue circles at each data point. Another example would be fsolve(fxn,x0) vs fsolve(fxn,x0,options).
Is there a simple way to check if any of the varargin inputs are a specific string or format so the function runs smooth for different user inputs? Thanks in advance!


DGM 2021 年 4 月 9 日
編集済み: DGM 2021 年 4 月 9 日
For the case where looking for a specific string:
varargin = {'aaa','bbb',13,{'a','b'},[12 34],'ccc'} % let's pretend we have some varargin
% test to see if a certain string is in varargin
vararginhas_bbb = strismember('bbb',varargin) % returns true
vararginhas_b = strismember('b',varargin) % returns false
where strismember() is the following function:
function yeah=strismember(thing,setofthings)
% Returns true if the character array STRING is a member of the
% cell array SETOFSTRINGS. This is generally faster than using
% ismember() -- about 2x as fast in recent versions, and up to
% 50x as fast in older versions. Numeric inputs are not supported.
% See also: ismember, strcmp
If you wanted to see if varargin contained any arguments of a certain type:
vararginhas_cell = any(cellfun(@iscell,varargin)) % returns true
vararginhas_struct = any(cellfun(@isstruct,varargin)) % returns false
I'm sure there are better, more preferred ways
  3 件のコメント
Samuel Brewton
Samuel Brewton 2021 年 4 月 9 日
I'll look into it then, thank you again!


その他の回答 (0 件)


Find more on Argument Definitions in Help Center and File Exchange


Community Treasure Hunt

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

Start Hunting!

Translated by