Optional Arguments in Function as Struct Input

I have a Matlab function with many optional arguments which I want to call with these arguments recursively... This is just a short example, my real code is much more complexe and I don't want to share it here... I know that this function seems kind of nonesense.
function [out] = calculateHatches(vec, args)
arguments
vec
args.Limit = 0
args.Color = 'red'
args.Time = '12:00'
% (and many more argumnts)
end
% some calculations that give me out
out = []
if args.Limit==0
for i=1:10
nargs = args;
nargs.Limit = 1;
% n arguments might change here ...
% calculateHatches(vec,'Limit',nargs.Limit,'Color',nargs.Color,'Time',nargs.Time)
nout = calculateHatches(vec,nargs)
out = [out, nout]
end
end
end
However, this won't work, is there a way to makt it work?
calculateHatches(vec,nargs)
But I have too many optional arguments that change over time of programming too much, that I don't want to write it into the code. This would mean a lot of administration work.
calculateHatches(vec,'Limit',nargs.Limit,'Color',nargs.Color,'Time',nargs.Time)

 채택된 답변

Steven Lord
Steven Lord 2025년 1월 14일

0 개 추천

Use the namedargs2cell function.

댓글 수: 3

Ingo Hermann
Ingo Hermann 2025년 1월 15일
편집: Ingo Hermann 2025년 1월 15일
This function is splitting the arguments into cells, but I still cannot give it as input argument to calculateHatches like this. However, I can use eval to make it work somehow but this is not really nice ^^...
calculateHatches(vec,namedargs2cell(nargs))
Invalid argument at position 2. Function requires exactly 1 positional input(s).
% Fix using eval:
strVal = ['[out] = calculateHatches(vec'];
allArgs = namedargs2cell(nargs);
for i=1:2:size(allArgs,2)
strVal = [strVal,',"',char(allArgs{i}),'"',',allArgs{',char(num2str(i+1)),'}'];
end
strVal = [strVal,' );'];
eval(strVal);
"However, I can use eval to make it work somehow but this is not really nice ^^..."
EVAL is the opposite of nice. The MATLAB approach is to use a comma-separated list:
tmp = namedargs2cell(nargs);
out = calculateHatches(vec,tmp{:});

Thank you, that was what I was looking for!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

릴리스

R2023a

질문:

2025년 1월 14일

댓글:

2025년 1월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by