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

 採用された回答

Francois Steiner
Francois Steiner 2017 年 2 月 6 日

0 投票

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 件のコメント

Walter Roberson
Walter Roberson 2017 年 2 月 6 日
You have to pass p as the first argument to parse
Francois Steiner
Francois Steiner 2017 年 2 月 6 日
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
Guillaume
Guillaume 2017 年 2 月 6 日
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.
Walter Roberson
Walter Roberson 2017 年 2 月 6 日
Actually it is okay to accept your own Answer if you were the one who figured out the solution.

サインインしてコメントする。

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2017 年 2 月 5 日

1 投票

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

1 件のコメント

Francois Steiner
Francois Steiner 2017 年 2 月 6 日
編集済み: Francois Steiner 2017 年 2 月 6 日
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