how to pass keyword arguments to a function via a struct
Mostrar comentarios más antiguos
In recent versions of Matlab, functions can declare optional arguments with default values that get automatically packed into a struct e.g.,
function examplefn(x)
arguments
x.a (1,1) double = 12
x.b (1,1) double = 7
end
With such a declaration, the function is called via examplefn('a', 8, 'b', 9) (or just examplefn('a',8)), and the examplefn function body can now use x.a and x.b as variables. Suppose I have written such a function, and its caller (rather than the function) has the arguments in a struct:
y = struct('a', 8, ,'b', 9);
What is the way to pass y as an input argument to examplefn? I'd like to be able to say something like: examplefn(unpack(y)). Obviously, I could spell it out: examplefn('a', y.a, 'b', y.b) but expanding in this way partly defeats the purpose of having optional and keyword arguments in the first place and makes it fragile to chain a sequence of functions that share keyword/optional arguments. Thanks.
2 comentarios
dpb
el 16 de En. de 2023
At this time there is no syntax to do anything other than pass the name-value parameter pairs explicitly.
I didn't 'spearmint; you might be able to write an anonymous function that would do the unwrapping to the string to pass, but then you would have to revert to eval to execute the result; MATLAB wouldn't know what to do with the string as an argument list.
Stephen Vavasis
el 16 de En. de 2023
Movida: Matt J
el 16 de En. de 2023
Respuesta aceptada
Más respuestas (2)
y = struct('a',8,'b', 9);
x=examplefn(y)
x=examplefn('a',8,'b',9)
function x=examplefn(varargin)
p=inputParser();
addParameter(p,'a',12);
addParameter(p,'b',7);
addParameter(p,'c',100);
parse(p,varargin{:});
x=p.Results;
end
Matt J
el 16 de En. de 2023
Movida: Walter Roberson
el 16 de En. de 2023
0 votos
1 comentario
Stephen Vavasis
el 16 de En. de 2023
Movida: Walter Roberson
el 16 de En. de 2023
Categorías
Más información sobre Data Type Identification 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!