问题
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.
回答1:
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)
executesexpression
, a character vector or string scalar containing any valid MATLAB® expression using variables in the workspacews
.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.
来源:https://stackoverflow.com/questions/51476571/how-do-i-get-the-value-of-a-simulink-struct-from-the-workspace-within-a-matlab-f