How to pass a struct as name-value-pairs to a function?
75 views (last 30 days)
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.
One particular function that use Name-Value pairs as input is the GlobalSearch function in MATLAB.
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)
Matt J on 1 Jul 2019
Edited: Matt J on 1 Jul 2019
Some functions may enable this (in particular, those that use inputParser to parse string-value pairs will always accept a struct), but clearly not all functions, as you found out when you ran your example. However, you can always pre-convert a struct to a cell of string value pairs using the utility below.
%Turns a scalar struct S into a cell of string-value pairs C
%If S is a cell already, it will be returned unchanged.
error 'Input must be a scalar struct or cell';