フィルターのクリア

How to pass a struct as name-value-pairs to a function?

93 ビュー (過去 30 日間)
Pontus Vikstål
Pontus Vikstål 2019 年 7 月 1 日
コメント済み: Markus Leuthold 2022 年 5 月 10 日
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
Matt J 2019 年 7 月 1 日
編集済み: Matt J 2019 年 7 月 1 日
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(:).';
  1 件のコメント
Pontus Vikstål
Pontus Vikstål 2019 年 7 月 1 日
This seemed to work for me thank you!

サインインしてコメントする。

その他の回答 (1 件)

Hyeokjin Jho
Hyeokjin Jho 2021 年 3 月 30 日
  3 件のコメント
Matt J
Matt J 2022 年 4 月 25 日
Yes, perhaps an attribute syntax:
function myfunction(options)
arguments(StructExpand=true)
end
end
Markus Leuthold
Markus Leuthold 2022 年 5 月 10 日
Matt, sounds like a good idea!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeString についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by