Named arguments in Matlab?
Mostrar comentarios más antiguos
I am digging through some old code that does named function arguments:
function self = Renderer(varargin)
opt = varopts(varargin,...
'scene','linuss', ...
'renderer', 'iray', ...
'host', 'localhost', ...
'port', 24242, ...
'samples', 100, 'render_iterate',4);
I'm wondering if matlab has a built in way to do this? Below is the helper function varopts... Can anyone explain what it's doing?
function [opt,xtra] = varopts(optlist, varargin)
[opt,xtra] = deal(struct());
% parse the field names and their default values
for n=1:2:length(varargin)
opt.((varargin{n})) = varargin{n+1};
end
% I forget why I do this
if numel(optlist) == 1 && iscell(optlist{1})
optlist = optlist{1};
end
% if an odd number of arguments is supplied, then
% the first one is assumed to be a filename or structrure to
% supply default override values
if mod(numel(optlist),2)
opt = load_defaults(opt, optlist{1});
optlist = optlist(2:end);
end
% now apply any override values
for n=1:2:length(optlist)
if nargin == 1 || isfield(opt,optlist{n})
opt.((optlist{n})) = optlist{n+1};
else
xtra.((optlist{n})) = optlist{n+1};
end
end
function opt = load_defaults(opt, defaults)
if isstruct(defaults)
% do nothing
else
[~,~,ext] = fileparts(defaults);
if strcmp(ext, '.mat') || (strcmp(ext, '') && exist(defaults,'file') ~= 2)
defaults = load(defaults);
elseif exist(defaults,'file') == 2
defaults = loadm(defaults);
else
error('varopts with odd number of arguments, expects first argument to be a config file');
end
end
% now copy over the overrided values
fields = fieldnames(opt);
for n=1:length(fields)
if isfield(defaults,fields{n})
opt.(fields{n}) = defaults.(fields{n});
end
end
function out = loadm(filename__)
run(filename__);
clear filename__;
variables = who();
out = struct();
for n=1:numel(variables)
out.(variables{n}) = eval(variables{n});
end
1 comentario
Cris LaPierre
el 25 de Oct. de 2022
Perhaps this Answer is of interest
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Interactive Control and Callbacks en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!