Being given the name of a variable as a string (in my case the name of an existing Simulink.Parameter variable in the workspace selected by the user as a design variable for optimization), I would like to be able to access the properties of the object such as Simulink.Parameter.Min, Simulink.Parameter.Max, Simulink.Parameter.Value without using eval(). So far I am employing the (very ugly) solution
varnames = {'var1','var2'}; % Simulink.Parameter objects existing in workspace
objects = cell(length(varnames),1);
for i = 1:length(varnames)
eval(['objects{i}=', varnames{i}, ';']) % Store objects in a cell array
end
Ideally, this would look like:
objects = get_object_handles_from_string(varnames);
value_1 = object{1}.Value(:);
Otherwise a method returning the variable name given the object handle would also be acceptable.
Methods that I found not to be working but might be useful otherwise:
Thanks!
This is exactly what eval
is for. Yes, you should avoid using eval
, but if you want to have a user type in stuff to be evaluated, you need eval
. Or evalin
if you want to evaluate it in the base or caller workspace rather than the current workspace.
There are no such thing as "object handles" (except graphics objects, but that is not what you are talking about here). There are variables owning arrays of data, that is it.
If you don't trust your users, don't use eval
. They could type in anything, including clear all
or !\rm -rf /*
(or whatever the Windows equivalent is to erase the disk).
In this case, and presuming there is a limited set of variables that the user can specify, do
var1 = 1;
var2 = 2;
varnames = {'var1','var2'}; % Simulink.Parameter objects existing in workspace
objects = cell(size(varnames));
for i = 1:numel(varnames)
objects{i} = get_variable_value(varnames{i}) % Store objects in a cell array
end
function val = get_variable_value(name)
switch name
case 'var1'
val = evalin('caller',var1);
case 'var2'
val = evalin('caller',var2);
otherwise
error('Illegal variable name')
end