Different Function Input Formats
8 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
DGM
il 9 Apr 2021
Modificato: DGM
il 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)
% 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 Commenti
DGM
il 9 Apr 2021
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
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Data Type Identification in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!