MATLAB Answers

Different Function Input Formats

조회 수: 2(최근 30일)
Samuel Brewton
Samuel Brewton 9 Apr 2021
댓글: Samuel Brewton 9 Apr 2021
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 9 Apr 2021
편집: DGM 9 Apr 2021
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 9 Apr 2021
I'll look into it then, thank you again!

댓글을 달려면 로그인하십시오.

추가 답변(0개)


Community Treasure Hunt

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

Start Hunting!

Translated by