Search code examples
matlabglobal-variablessimulinkdata-dictionary

How do I get the value of a Simulink struct from the workspace within a MATLAB function?


I need to access the values of variables in MATLAB's workspace of type Simulink.parameter:

CAL_vars = dsdd('find','/path/CAL','ObjectKind','Variable','Property',{'name' 'Class' 'value' 'CAL'}) 
%gets ids of variables in data dictionary
i = 10
for i=1:length(CAL_vars)
       var_name = dsdd('GetAttribute',CAL_vars(i),'name');
       % gets names of variables in data dict
       var_eval = eval(var_name); % this works in standalone script and it does exactly 
       % what I need, but once i put it in the function I need this for, it returns error
       if (length(var_eval.Value) ==1)
           if (var_eval.Value == true)
               var_eval.Value = 1;
           elseif (var_eval.Value == false)
               var_eval.Value = 0;
           else
           end
       end
       % do something with the Value
       if (errorCode ~= 0)
          fprintf('\nSomething is wrong at %s\n', var_name)
       end
end

The problem arises because the structs are of made by Simulink and give error, when I try to call eval(name_of_var): Undefined function 'eval' for input arguments of type 'Simulink.Parameter'.

Curiously, it seems to function properly in a stand-alone script but once I plug it into the larger function, it stops working and starts displaying error saying

Error using eval
Undefined function or variable 'name_of_var'.

The function is clearly in the workspace.


Solution

  • Curiously, it seems to function properly in a stand-alone script but once I plug it into the larger function, it stops working

    This is the expected behaviour. A function has its own workspace and can't directly access variables in the base workspace.

    You could try using evalin instead of eval, and specify the base workspace:

    evalin(ws, expression) executes expression, a character vector or string scalar containing any valid MATLAB® expression using variables in the workspace ws. ws can have a value of 'base' or 'caller' to denote the MATLAB base workspace or the workspace of the caller function.

    In general though, there are lots of reasons for trying to avoid using eval if at all possible (see the MATLAB help for eval) and it would be best if you could find a different way of getting this data.