- Remove "width" as a separate function parameter and include it within "varargin".
- Adjust the parsing of "width" within "inputParser" accordingly.
- Access "width" through "p.Results.width".
Does inputparser duplicate required fields?
3 views (last 30 days)
Show older comments
It appears that inputparser duplicates required fields in a function. For example in the documentation example, (shown below), width exists within the function's space both as 'width' and p.Results.width. Are these copies of each other taking up twice the space of either one? I ask because it would seem to be undesireable to create duplicates if a required parameter is a very large array or table for example. Perhaps it's not an issue or there is a recommended way to handle such scenarios, (perhaps declaring the argument as optional, even though required, so that the call would become a = findArea(varargin)?).
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);
addRequired(p,'width',validScalarPosNum);
addOptional(p,'height',defaultHeight,validScalarPosNum);
addParameter(p,'units',defaultUnits,@isstring);
addParameter(p,'shape',defaultShape,...
@(x) any(validatestring(x,expectedShapes)));
parse(p,width,varargin{:});
a = p.Results.width*p.Results.height;
end
0 Comments
Answers (1)
Himanshu
on 27 Sep 2023
Hello,
I understand that you are facing an issue with the "inputParser" function in MATLAB, specifically regarding the duplication of required fields. The issue occurred because a required parameter, such as "width" in your example, appears to exist twice: once as a function parameter (i.e., "width") and once as a field in the "p.Results" structure (i.e., "p.Results.width").
In MATLAB, when you use "inputParser", the parsed inputs are stored in the "Results" property of the "inputParser" object. This is designed to provide a consistent interface for accessing input parameters, especially when dealing with optional parameters, parameter-value pairs, or parameters with default values. Each field of the "Results" structure corresponds to the name of an argument in the input parser scheme. The "parse" function populates the "Results" property.
You can follow the below steps to fix the issue:
You can refer to the below documentation to understand more about the "inputParser" and the "varargin" functions in MATLAB.
0 Comments
See Also
Categories
Find more on Argument Definitions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!