Parsing default function arguments: why isn't it better???
3 ビュー (過去 30 日間)
古いコメントを表示
Hi all,
in octave, if i have a function fff where the 3rd argument is optional, i can give it a default value by doing
function fff(argv1, argv2, opt1=3)
This seems not to work in matlab. Thus i have to do sth like:
function fff(arg1,arg2,opt1)
if nargin < 3
opt1 = 3
end
and now the question: why??? Adding so many unnecessary lines! This seems like the worst syntax option possible. Can it get any better? I really appreciate your answer since i did not use matlab that often yet!
thx oxy
回答 (3 件)
Azzi Abdelmalek
2014 年 3 月 18 日
You have described a simple case, what if the situation is more complicated?
0 件のコメント
David Young
2014 年 3 月 18 日
The main tool MATLAB offers to handle optional arguments would look like this in your example:
function fff(arg1,arg2,varargin)
inp = inputParser;
inp.addOptional('opt1', 3);
inp.parse(varargin{:});
opt1 = inp.Results.opt1;
So although your own solution seems long and cumbersome to you, there is an even longer and more cumbersome way to do it available. As this suggests, your solution is about as neat as it gets provided you don't want validation - MATLAB simply does not include the syntax you show for Octave.
There are some contributions on the FEX that provide a neater-looking setup than the inputParser approach, and it might be worth looking into those - but it will still require code in the body of your function.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!