How to pass a struct as name-value-pairs to a function?
Mostra commenti meno recenti
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)
Risposta accettata
Più risposte (1)
Hyeokjin Jho
il 30 Mar 2021
4 voti
try namedargs2cell
3 Commenti
Markus Leuthold
il 25 Apr 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
il 25 Apr 2022
Yes, perhaps an attribute syntax:
function myfunction(options)
arguments(StructExpand=true)
end
end
Markus Leuthold
il 10 Mag 2022
Matt, sounds like a good idea!
Categorie
Scopri di più su Logical in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!