我遇到了障碍,我试图在SIMULINK中的EML(嵌入式Matlab)功能块内迭代MATLAB工作区中形成的结构。以下是一些示例代码:
% Matlab code to create workspace structure variables
% Create the Elements
MyElements = struct;
MyElements.Element1 = struct;
MyElements.Element1.var1 = 1;
MyElements.Element1.type = 1;
MyElements.Element2 = struct;
MyElements.Element2.var2 = 2;
MyElements.Element2.type = 2;
MyElements.Element3 = struct;
MyElements.Element3.var3 = 3;
MyElements.Element3.type = 3;
% Get the number of root Elements
numElements = length(fieldnames(MyElements));
MyElements是SIMULINK中MATLAB功能块(EML)的总线类型参数。以下是我遇到麻烦的地区。我知道我的struct中的元素数量,我知道名称,但元素的数量可以随任何配置而改变。所以我不能根据Element名称进行硬编码。我必须遍历EML块中的结构。
function output = fcn(MyElements, numElements)
%#codegen
persistent p_Elements;
% Assign the variable and make persistent on first run
if isempty(p_Elements)
p_Elements = MyElements;
end
% Prepare the output to hold the vars found for the number of Elements that exist
output= zeros(numElements,1);
% Go through each Element and get its data
for i=1:numElements
element = p_Elements.['Element' num2str(i)]; % This doesn't work in SIMULINK
if (element.type == 1)
output(i) = element.var1;
else if (element.type == 2)
output(i) = element.var2;
else if (element.type == 3)
output(i) = element.var3;
else
output(i) = -1;
end
end
关于如何在SIMULINK中迭代结构类型的任何想法?另外,我不能使用像num2str这样的外部函数,因为这是在目标系统上编译的。
答案 0 :(得分:2)
我相信您正在尝试将dynamic field names用于结构。正确的语法应该是:
element = p_Elements.( sprintf('Element%d',i) );
type = element.type;
%# ...