How to pass a struct as name-value-pairs to a function?
Mostrar comentarios más antiguos
Is it possible to convert a struct to name-value-pairs that is then fed to a function that takes Name-Value pairs as input arguments? The fieldname of the struct would represent the Name and and the fieldvalue the Value of the Name-Value pairs.
gs = GlobalSearch(Name,Value,...)
For example is the following possible
% I want this
gs = GlobalSearch('BasinRadiusFactor',.5,'NumTrialPoints',400)
% To be equal to this
options.BasinRadiusFactor = 0.5
options.NumTrialPoints = 400
gs = GlobalSearch(options)
Respuesta aceptada
Más respuestas (1)
Hyeokjin Jho
el 30 de Mzo. de 2021
4 votos
try namedargs2cell
3 comentarios
Markus Leuthold
el 25 de Abr. de 2022
Unfortunately, this is still quite cumbersome since you cannot use it in one line. If you want to use this in conjunction with an
arguments
end
block, you need to convert the cell into separate arguments
options.BasinRadiusFactor = 0.5
options.NumTrialPoints = 400
optionsCell = namedargs2cell(options)
myfunction(optionsCell{:})
Why did Mathwork not allow to use a struct for a arguments/end block the same way it was possible with inputParser?
Matt J
el 25 de Abr. de 2022
Yes, perhaps an attribute syntax:
function myfunction(options)
arguments(StructExpand=true)
end
end
Markus Leuthold
el 10 de Mayo de 2022
Matt, sounds like a good idea!
Categorías
Más información sobre Logical 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!