Best practice for updating default parameter values inside a function, preferably with struct
Show older comments
I apologize if this question has been asked in some form or another. Feel free to point me to any existing answers...
My use case is fairly straightforward:
I have a simulation which has many different parameters. I have packaged my simulation into a function, which contains default values for these parameters. However, I would like to be able to call my simulation function, and pass in an input to override any one or all of my default parameter values. Since there are a large number of parameters, I would find it convenient to pass in the input as a structure.
So say for example:
function output = mySim(inputStruct)
%Assign defaults:
x0 = 1;
y0 = 2;
z0 = 3;
vx0 = 0;
vy0 = 0;
vz0 = 1;
dt = 0.1;
% Desired update code....
%-> check if inputStruct exists
%-> update any of the parameters with the value contained in inputStruct
output.x = x0+vx0*dt;
output.y = y0+vy0*dt
output.z = y0+vz0*dt
end
I can think of any number of, and probably dumb, ways to do this. One such way is a helper function I wrote, which will read through a struct and load all the fields as variables into the local workspace. Here it is pasted below for reference:
function load_struct_vars(inp)
% Extracts fields from structure and creates new variable with that
% fieldname and value in the calling workspace.
names=fieldnames(inp);
values=struct2cell(inp);
for i=1:length(names)
assignin('caller',names{i},values{i});
end
end
This achieves the desired result of overwriting the default values with the new ones from the struct, and also gives me the convenience of not having to make any corresponding edits to the update code. I.e., if I create additional default parameters in my simulation function, I can override these values simply by adding the new var as a field in my input struct.
My solution however, relies on the assignin() function, which I have learned is a really bad idea, and not good practice. I have noticed myself that it is really slow as well.
Hence my question: what is a recommended best practice for achieving the result I have outlined?
Thanks in advance!
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!