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

 Réponse acceptée

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 commentaires

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.

Connectez-vous pour commenter.

Plus de réponses (1)

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

1 commentaire

Francois Steiner
Francois Steiner le 6 Fév 2017
Modifié(e) : Francois Steiner le 6 Fév 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

Connectez-vous pour commenter.

Catégories

En savoir plus sur Argument Definitions dans Centre d'aide et File Exchange

Produits

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by