Reputation: 1668
I have a a workspace called "parameters.mat", which contains many variables (really, constants) used by several methods throughout my simulation. The reason that I want these in one workspace is to have them in a handy place for the user to change.
I want to access these variables within class methods. I've found two ways of doing this, and I'd like to know which one is considered better (or perhaps if there's an even better way):
Load the workspace before anything else, as the base workspace, and whenever I want to use a variable from it within a method, I call evalin('base', 'variable_name')
first.
Load the workspace within the method whenever I need it. This works, but it gives me a warning when I use an undefined variable name in the rest of the method (because MATLAB doesn't know it will be loaded from a workspace). Is there a clean way to remove this warning?
Upvotes: 1
Views: 103
Reputation: 8477
Probably the cleanest way to do this is to use a wrapper function. Building on my comment, assuming your parameter constants are in a file parameters.mat
:
function value = param(name)
s = load('parameters.mat');
value = getfield(s, name);
Now you can use a syntax like
var = param('name');
wherever you need the value of this variable. This way to do it is easily understandable to humans, and transparent to Matlab's code checker. You can also use param('name')
directly in your computations, without assigning the value to a local variable.
If the parameter file contains more than just a few numbers, and loading it time after time slows down things, you can cache the data in a persistent variable:
function value = param(name)
persistent s
if isempty(s)
s = load('parameters.mat');
end
value = getfield(s, name);
Now the mat-file is read only on the first call to param()
. The persistent variable s
remains until the next clear all
(or similar, see clear) or the end of the Matlab session. A drawback of this is that if you changed the mat-file, you have to clear all
in order to make param()
re-read it.
If on the other hand your mat-file does only consist of a few numbers, maybe a mat-file is not even necessary:
function value = param(name)
s.x0 = 1;
s.epsilon = 1;
s.dt = 0.01;
value = getfield(s, name);
With this approach the function param()
is no longer a wrapper, but a central location where you store parameter values instead of a mat-file.
Upvotes: 2