varargin error for optional inputs

7 次查看(过去 30 天)
I was running this code
%%Parse Inputs
p = inputParser;
p.FunctionName = 'linear_inversion_ksn';
% required inputs
addRequired(p,'DEM', @(x) isa(x,'GRIDobj'));
% optional inputs
addOptional(p,'crita', 1e6, @(x) isscalar(x));
addOptional(p,'mn', 0.5, @(x) isscalar(x));
addOptional(p,'chi_inc', 1, @(x) isscalar(x));
addOptional(p,'gam', 10, @(x) isscalar(x));
addOptional(p,'flowOption', []);
parse(p,DEM, varargin{:});
DEM = p.Results.DEM;
And got an error like this
>> parse(p,DEM, varargin{:});
Brace indexing into the result of a function call is not supported. Assign the result
of 'varargin' to a variable first, then brace index into it.
Kindly help me in fixing it

采纳的回答

Voss
Voss 2024-6-27
The problem is that varargin is not defined. Typically varargin refers to input arguments passed to a function. The code you are running appears to be a script, so varargin is not needed, since scripts take no input arguments.
  • If your code is a script, you can remove varargin{:} and just use parse(p,DEM);
  • If your code is a function and you need to use varargin to handle input arguments that may or may not be passed in, then you should define varargin in the function definition, as shown below, for example.
function DEM = test_DEM(DEM,varargin)
%%Parse Inputs
p = inputParser;
p.FunctionName = 'linear_inversion_ksn';
% required inputs
addRequired(p,'DEM', @(x) isa(x,'GRIDobj'));
% optional inputs
addOptional(p,'crita', 1e6, @(x) isscalar(x));
addOptional(p,'mn', 0.5, @(x) isscalar(x));
addOptional(p,'chi_inc', 1, @(x) isscalar(x));
addOptional(p,'gam', 10, @(x) isscalar(x));
addOptional(p,'flowOption', []);
parse(p,DEM, varargin{:});
DEM = p.Results.DEM;
end
References:
  2 个评论
Voss
Voss 2024-6-28
You're welcome! Any questions, please let me know. Otherwise, please Accept this answer. Thanks!

请先登录,再进行评论。

更多回答(1 个)

Ashutosh Thakur
Ashutosh Thakur 2024-6-27
Hello Uma,
The error you are facing is due to the way in which MATLAB handles the varargin input. I can see that you are trying to pass varargin with brace indexing to the parse function. This behavior is not supported which is causing the issue. Instead, I recommend assigning the varargin to the different variable and pass that variable with the brace indexing to the parse function. https://www.mathworks.com/help/matlab/ref/varargin.html.
Following sample code can be referred for the above-mentioned approach:
function abc(varargin)
% Assign varargin to a variable first
vararginCell = varargin;
disp(vararginCell{1})
disp(vararginCell{2})
end
abc(1,2)
1 2
I hope that this helps you!

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by