Different Function Input Formats
8 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
采纳的回答
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)
% 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 个评论
DGM
2021-4-9
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Identification 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!