Effacer les filtres
Effacer les filtres

Parsing default function arguments: why isn't it better???

3 vues (au cours des 30 derniers jours)
oxy
oxy le 18 Mar 2014
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

Réponses (3)

Azzi Abdelmalek
Azzi Abdelmalek le 18 Mar 2014
You have described a simple case, what if the situation is more complicated?

oxy
oxy le 18 Mar 2014
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 le 18 Mar 2014
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.

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by