Does inputparser duplicate required fields?

4 ビュー (過去 30 日間)
RM
RM 2022 年 7 月 12 日
回答済み: Himanshu 2023 年 9 月 27 日
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

回答 (1 件)

Himanshu
Himanshu 2023 年 9 月 27 日
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:
  1. Remove "width" as a separate function parameter and include it within "varargin".
  2. Adjust the parsing of "width" within "inputParser" accordingly.
  3. Access "width" through "p.Results.width".
You can refer to the below documentation to understand more about the "inputParser" and the "varargin" functions in MATLAB.

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by