Function to create struct with parameters

1 ビュー (過去 30 日間)
Felix Müller
Felix Müller 2021 年 4 月 26 日
コメント済み: Felix Müller 2021 年 4 月 27 日
Currently I have a function with settings/parameters for my program, where all parameters are written into a struct like "inp.month = 7;" so that I can pass the struct "inp" to functions afterwards. Is it possible to have all the assignments in the function without the struct, eg "month = 7;" and at the end somehow get 'all variables in this function' into the struct "inp". Something like "inp = <gather all variables assigned in this function>", and then have the struct be the output. It would add readability in my opinion and also I thought this to be easy, but didn't find a good solution yet and thought I'd ask here.
Cheers
Felix
  5 件のコメント
Felix Müller
Felix Müller 2021 年 4 月 27 日
Well, that might not be so obvious before thinking about it, eh?

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

採用された回答

Jeff Miller
Jeff Miller 2021 年 4 月 26 日
Maybe you would like something like this?
month = 1;
year = 1951;
day = 11;
inp = CreateStruct(month,day,year)
function outstruc = CreateStruct(varargin)
% Create a structure with the input variables as fields.
outstruc = struct;
for iField=1:numel(varargin)
sfName = inputname(iField);
outstruc.(sfName) = varargin{iField};
end
end
  2 件のコメント
Stephen
Stephen 2021 年 4 月 27 日
"Do you think there are any drawbacks...?"
Slower code: "Avoid functions that query the state of MATLAB such as inputname, which, whos, exist(var), and dbstack. Run-time introspection is computationally expensive."

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

その他の回答 (2 件)

Walter Roberson
Walter Roberson 2021 年 4 月 26 日
The following code is not recommended.. but it should work.
ZZ_filename = [tempname '.mat'];
save(ZZ_filename, '-struct', '-regexp', '^[^Z]', '^Z[^Z]');
inp = load(ZZ_filename);
delete(ZZ_filename);
If you already have variable names that begin with 'ZZ' then this code would have to be modified.
The purpose of the -regexp is to allow saving all of the variables except the over-head variable ZZ_filename .
  3 件のコメント
Felix Müller
Felix Müller 2021 年 4 月 26 日
Okay, thanks! I thought it might work without fiddling with the assignment of variables myself (eg with a function written exactly for this), but it might not.

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


Bruno Luong
Bruno Luong 2021 年 4 月 27 日
s = buildparams()
s = struct with fields:
a: 1 b: 2
function s = buildparams()
a = 1;
b = 2;
s = gathervars();
end
function s = gathervars()
vars = evalin('caller', 'whos');
for k=1:length(vars)
name = vars(k).name;
s.(name) = evalin('caller', name);
end
end

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by