Note that avoiding using evalin (or assignin, etc) has numerous advantages: it is faster, it does not overwrite preexisting values without warning, it does not make variables "magically" pop into existence in a workspace, it makes debugging much easier, it makes checking which variables have been defined much simpler, it makes adding (or setting) variable values simpler, etc,etc. Here are two simple solutions without slow and buggy evalin. Solution One: Hardcoded Values
function S = myConst()
S.a = 2;
S.b = 7;
S.c = 15;
S.name = 'My Name';
S.age = 105;
end
When you call this function it will return a structure with all of the given variables in it. This is trivial to use:
Solution Two: Settable Values
function val = myConst(name,val)
mlock
persistent S
if isempty(S)
S = struct();
end
switch nargin
case 0
val = fieldnames(S);
case 1
val = S.(name);
case 2
val = S.(name) = val;
end
end
This function lets you set and get any values that you wish:
>> myConst('a',2);
>> myConst('b',7);
>> myConst('c',15);
>> myConst('name','My Name');
>> myConst()
ans =
a
b
c
name
>> myConst('c')
ans = 15
0 Comments
Sign in to comment.