Passing arguments to varargin
Afficher commentaires plus anciens
Hi
Aesthetic detail:
I have a function using several parameters. These parameters have default values, but can be given as input if desired. I am doing this using varargin in the following format:
function y = my_fun(a,b, varargin)
% Default values
length = 0;
height = 2;
% Loading optional arguments
while ~isempty(varargin)
switch lower(varargin{1})
case 'length'
length = varargin{2};
case 'height'
height = varargin{2};
otherwise
error(['Unexpected option: ' varargin{1}])
end
varargin(1:2) = [];
end
% the actual function
y = a + b + length*height;
end
This works fine if I write the options directly into the function, e.g. my_fun(a,b,'length',2). What I would like to do is something like this:
options = {'length',1,'height',2};
my_fun(3,4,options);
I know that I can make it work by passing
options{:}
instead of just options, but is there a way to avoid that?
Thanks!
Réponse acceptée
Plus de réponses (2)
Sean de Wolski
le 29 Oct 2014
2 votes
Have you tried inputParser?
It provides a good framework for what you're trying to do.
1 commentaire
Adam
le 29 Oct 2014
Certainly it would provide a good, relatively simple, route into OOP for a first time, but if the solution you have works and you are pressed for time then just run with that.
You can also use a standard struct in place of a class to define the default arguments, it just isn't as neat as a struct has dynamic fields and you can't create a default struct without a function wrapper or similar.
Catégories
En savoir plus sur Argument Definitions dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!