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
Azzi Abdelmalek 2014-3-18
You have described a simple case, what if the situation is more complicated?

oxy
oxy 2014-3-18
Hi azzi,
right now i cannot imagine a situation where the octave syntax would be problematic. Can u guive us an example?
thx...

David Young
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.

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by