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

 Respuesta aceptada

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 comentarios

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.

Iniciar sesión para comentar.

Más respuestas (1)

Walter Roberson
Walter Roberson el 5 de Feb. de 2017
The variable name has to be varargin to be recognized as special, not varargList

1 comentario

Francois Steiner
Francois Steiner el 6 de Feb. de 2017
Editada: Francois Steiner el 6 de Feb. de 2017
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

Iniciar sesión para comentar.

Categorías

Más información sobre Argument Definitions en Centro de ayuda y File Exchange.

Productos

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by