Named arguments in Matlab?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
seth patterson
am 25 Okt. 2022
Beantwortet: Chunru
am 26 Okt. 2022
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 Kommentar
Akzeptierte Antwort
Chunru
am 26 Okt. 2022
Use arguments block (additionaly for default value, type and size check. doc arguments for more details)
self = Renderer(samples = 200)
function self = Renderer(opt)
arguments
opt.scene ='linuss'
opt.renderer ='iray'
opt.host ='localhost'
opt.port = 24242
opt.samples = 100
opt.render_iterate = 4
end
% other operations based on opt
disp(opt)
self = opt;
end
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Whos finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!