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

 Risposta accettata

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 Commenti

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.

Accedi per commentare.

Più risposte (1)

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

1 Commento

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

Accedi per commentare.

Categorie

Scopri di più su Argument Definitions in Centro assistenza e File Exchange

Prodotti

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by