How to pass a struct as name-value-pairs to a function?
    37 Ansichten (letzte 30 Tage)
  
       Ältere Kommentare anzeigen
    
    Pontus Vikstål
      
 am 1 Jul. 2019
  
    
    
    
    
    Kommentiert: Markus Leuthold
      
 am 10 Mai 2022
            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)
0 Kommentare
Akzeptierte Antwort
  Matt J
      
      
 am 1 Jul. 2019
        
      Bearbeitet: Matt J
      
      
 am 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.
function C=struct2pairs(S)
%Turns a scalar struct S into a cell of string-value pairs C
%
%  C=struct2pairs(S)
%
%If S is a cell already, it will be returned unchanged.
if iscell(S)
 C=S; return
elseif length(S)>1
    error 'Input must be a scalar struct or cell';
end
C=[fieldnames(S).'; struct2cell(S).'];
C=C(:).';
Weitere Antworten (1)
  Hyeokjin Jho
      
 am 30 Mär. 2021
        try namedargs2cell
3 Kommentare
  Matt J
      
      
 am 25 Apr. 2022
				Yes, perhaps an attribute syntax:
function myfunction(options)
 arguments(StructExpand=true)
 end
end
Siehe auch
Kategorien
				Mehr zu Argument Definitions finden Sie in Help Center und File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!