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
DGM 2021년 4월 9일
편집: DGM 2021년 4월 9일

1 개 추천

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)
% YEAHITIS=STRISMEMBER(STRING,SETOFSTRINGS)
% 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
yeah=~isempty(find(strcmp(thing,setofthings),1));
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일
This was super helpful, thank you!
Would you be able to explain how the @iscell and @isstruct works at all? What is it specifically that would make isstruct return true?
iscell(myvariable) % returns true if myvariable is a cell array
isstruct(myvariable) % returns true if myvariable is a struct array
it would be equivalent of doing
strcmp('cell',class(myvariable))
and so on.
There are a bunch of similar test functions. Try
help isa
for more
Samuel Brewton
Samuel Brewton 2021년 4월 9일
I'll look into it then, thank you again!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Type Identification에 대해 자세히 알아보기

제품

질문:

2021년 4월 9일

댓글:

2021년 4월 9일

Community Treasure Hunt

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

Start Hunting!

Translated by