如何从MATLAB函数中的工作区中获取Simulink结构的值? [英] How do I get the value of a Simulink struct from the workspace within a MATLAB function?
问题描述
我需要访问类型为 Simulink.parameter
的MATLAB工作区中的变量值:
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
出现问题因为结构是Simulink制作的,并且给出错误,所以当我尝试调用eval(name_of_var)时:对于类型为'Simulink.Parameter'的输入参数,未定义函数'eval'。
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.
推荐答案
奇怪的是,它似乎可以在独立脚本中正常运行,但是一旦我将它插入较大的函数中,
就会停止工作
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.
您可以尝试使用 evalin
而不是 eval
,然后指定 base
工作区:
You could try using evalin
instead of eval
, and specify the base
workspace:
evalin(ws,expression)
使用工作区<$ c中的变量
执行expression
,包含任何有效MATLAB®表达式的字符向量或
字符串标量。 $ c> ws 。ws
的值可以为'base'
或'caller'
到
表示MATLAB基本工作空间或调用者
函数的工作空间。
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.
,有很多原因试图避免使用 eval
(请参见MATLAB帮助中的 eval
)最好是找到其他获取数据的方法。
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.
这篇关于如何从MATLAB函数中的工作区中获取Simulink结构的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!