Search code examples
matlabsimulinkhandle

Get object handle given the name as a string (MATLAB)


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:

  • whos finds variable names and properties in the current workspace but no handles.
  • inputname returns the variable name of an explicit function input as a string but does not work for cell arrays of objects (see this question).
  • str2func returns a function handle with a string as input but does not enable access to attributes.
  • findobj returns objects given an array of objects to iterate over which I do not have. Might there be a method returning all workspace variable handles as an array?

Thanks!


Solution

  • 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