Function to create struct with parameters
Afficher commentaires plus anciens
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 commentaires
Matt J
le 26 Avr 2021
A better alternative is to automate the coding of the assignments with this:
Felix Müller
le 26 Avr 2021
Stephen23
le 26 Avr 2021
"I thought this to be easy"
Nope. While there are a few approaches to achieve this, they will all add complexity and make your code slower.
Bruno Luong
le 27 Avr 2021
This request is interesting only for lazy programmers who wants to make a quick and dirty code.
Just create a struct with the list of variables that you control explicitly.
Felix Müller
le 27 Avr 2021
Réponse acceptée
Plus de réponses (2)
Walter Roberson
le 26 Avr 2021
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 commentaires
Felix Müller
le 26 Avr 2021
Walter Roberson
le 26 Avr 2021
Then you will need to write code that uses dynamic variable naming, which is not at all recommended.
Hint: who() returns names of variables.
Felix Müller
le 26 Avr 2021
s = buildparams()
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
Catégories
En savoir plus sur Structures dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!