How to pass a struct as name-value-pairs to a function?
Show older comments
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)
Accepted Answer
More Answers (1)
Hyeokjin Jho
on 30 Mar 2021
4 votes
try namedargs2cell
3 Comments
Markus Leuthold
on 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
on 25 Apr 2022
Yes, perhaps an attribute syntax:
function myfunction(options)
arguments(StructExpand=true)
end
end
Markus Leuthold
on 10 May 2022
Matt, sounds like a good idea!
Categories
Find more on Argument Definitions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!