How to pass a struct as name-value-pairs to a function?
Afficher commentaires plus anciens
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)
Réponse acceptée
Plus de réponses (1)
Hyeokjin Jho
le 30 Mar 2021
4 votes
try namedargs2cell
3 commentaires
Markus Leuthold
le 25 Avr 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
le 25 Avr 2022
Yes, perhaps an attribute syntax:
function myfunction(options)
arguments(StructExpand=true)
end
end
Markus Leuthold
le 10 Mai 2022
Matt, sounds like a good idea!
Catégories
En savoir plus sur Argument Definitions dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!