How to use the "parse" function to create optional function inputs

Hello,
I am trying to use "parse" to create optional function inputs. Tried to replicate examples in the documentation (see below and attached) but I get the "too many arguments" error. Any idea? Thanks
my code below:
----------------
function []=testFun(A,varargList)
p = inputParser;
defaultNorm = 'L2';
validNorms = {'L1','L2'};
checkNorm = @(x) any(validatestring(x,validNorms));
addOptional(p,'lambda',0,@isnumeric)
addOptional(p,'norm',defaultNorm,checkNorm)
parse(A,varargList{:})
lambda = p.Results.lambda;
norm = p.Results.norm;
disp('input1 = ')
disp(A)
disp('lambda = ')
disp(lambda)
disp('norm = ')
disp (norm)
end

 采纳的回答

Hello,
I changed the name to varargin, but it still doesn't work, I have an error on the "parse" line. What am I missing?
See code below.
Thanks for your help.
François
function []=testFun(A,varargin)
p = inputParser;
defaultNorm = 'L2';
validNorms = {'L1','L2'};
checkNorm = @(x) any(validatestring(x,validNorms));
addOptional(p,'lambda',0,@isnumeric)
addOptional(p,'norm',defaultNorm,checkNorm)
parse(A,varargin{:})
lambda = p.Results.lambda;
norm = p.Results.norm;
disp('input1 = ')
disp(A)
disp('lambda = ')
disp(lambda)
disp('norm = ')
disp (norm)
end

4 个评论

You have to pass p as the first argument to parse
It works! Thanks Walter for your patience.
Below corrected code in case it can be of help to anyone.
All the best,
François
function []=testFun(A,varargin)
p = inputParser;
defaultNorm = 'L2';
validNorms = {'L1','L2'};
checkNorm = @(x) any(validatestring(x,validNorms));
addRequired(p,'A',@ischar);
addOptional(p,'lambda',0,@isnumeric)
addOptional(p,'norm',defaultNorm,checkNorm)
parse(p,A,varargin{:})
lambda = p.Results.lambda;
norm = p.Results.norm;
disp('A = ')
disp(A)
disp('lambda = ')
disp(lambda)
disp('norm = ')
disp (norm)
end
meta-comment: It's kind of bad form to accept your own answer to your own question, particularly as your answer is actually more of a comment on Walter's answer.
Actually it is okay to accept your own Answer if you were the one who figured out the solution.

请先登录,再进行评论。

更多回答(1 个)

The variable name has to be varargin to be recognized as special, not varargList

1 个评论

That simple - I thought any name would do. I really struggled with this one, many thanks for your help Walter, much appreciated. All the best, François

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Argument Definitions 的更多信息

产品

标签

Community Treasure Hunt

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

Start Hunting!

Translated by