필터 지우기
필터 지우기

Named arguments in Matlab?

조회 수: 4 (최근 30일)
seth patterson
seth patterson 2022년 10월 25일
답변: Chunru 2022년 10월 26일
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
Chunru 2022년 10월 26일
Use arguments block (additionaly for default value, type and size check. doc arguments for more details)
self = Renderer(samples = 200)
scene: 'linuss' renderer: 'iray' host: 'localhost' port: 24242 samples: 200 render_iterate: 4
self = struct with fields:
scene: 'linuss' renderer: 'iray' host: 'localhost' port: 24242 samples: 200 render_iterate: 4
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개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by