Named arguments in Matlab?
2 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
Chunru
2022-10-26
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!