I want to write a script experiment.m that will call a complicated function called encoder(...). encoder will involve a lot of settings that experiment.m is going to choose at runtime. At some point in experiment.m, the settings which encoder will use are created as variables (in this example there are two, in real life there can be dozens):
blocklength = [some derivation];
bitdepth = [some derivation];
I create a struct that stores these values under their names:
encoder_settings = struct();
encoder_settings.blocklength = blocklength;
encoder_settings.bitdepth = bitdepth;
And I write my encoder function like this:
function encoder_out = encoder(data, encoder_settings)
blocklength = encoder_settings.blocklength;
bitdepth = encoder_settings.bitdepth;
[...]
end
This works fine for code of moderate complexity, but after a while it becomes difficult to maintain the create-struct/load-struct blocks.
Alternatives I can think of don't seem great either:
encoderis usually very complex and calling the variables directly from the struct in its body makes the code difficult to read.- Do it dynamically using eval like this:
for s = fieldnames(my_struct)' eval([s{:},' = my_struct.', s{:}, ';']); end
Aucun commentaire:
Enregistrer un commentaire