what is varargin used for ?and how to use it? and can I change it to an ordinary input variable?
MATLAB: Varargin
varargin
Related Solutions
The dot between adaptfilt and lms is actually to depict that lms is a method that belongs to the adaptfilt class (the dot as in other languages is used as a separator between package, class and method names). For example, you can run:
>> which adaptfilt.lms
To see where the definition is located.
This does seem to be a limitation in the implementation of inputParser. Following code show a case where the parser will fail. In this code, the second optional input is a char array.
function a = findArea(width, varargin) defaultHeight = 1; defaultUnits = 'inches'; defaultShape = 'rectangle'; expectedShapes = {'square','rectangle','parallelogram'}; p = inputParser; validScalarPosNum = @(x) isnumeric(x) && isscalar(x) && (x > 0); validScalarPosNum2 = @(x) ischar(x); % <---- the optional parameter is char array
addRequired(p,'width',validScalarPosNum); addOptional(p,'height',defaultHeight,validScalarPosNum2); addParameter(p,'units',defaultUnits,@isstring); addParameter(p,'shape',defaultShape,... @(x) any(validatestring(x,expectedShapes))); parse(p,width,varargin{:}); a = p.Results; end
now call it like this
>> findArea(7, 'shape', 'square')Error using findArea (line 14)No value was given for 'square'. Name-value pair arguments require a namefollowed by a value.
I skipped the optional parameter height, but the parser failed to note that.
I guess this is done intentionally by MATLAB to avoid some kind of ambiguity in parsing the inputs. For example, in this case, it is easy to tell since we are using a single optional input. But consider a function that takes several optional inputs and parameters. In that case, it will become difficult for the parser to guess which values are optional inputs and which are parameters.
Note that the parser will only fail if you are taking character array as inputs for optional parameters. I guess the MATLAB expects that the character arrays should be input using parameters.
Best Answer