1

我遇到了一个障碍,我试图迭代在 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) 的总线类型参数。以下是我遇到麻烦的领域。我知道我的结构中的元素数量并且我知道名称,但是元素的数量可以随任何配置而改变。所以我不能根据元素名称进行硬编码。我必须遍历 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 这样的外部函数,因为这是要在目标系统上编译的。

4

1 回答 1

2

我相信您正在尝试对结构使用动态字段名称。正确的语法应该是:

element = p_Elements.( sprintf('Element%d',i) );
type = element.type;
%# ...
于 2011-10-29T12:23:30.827 回答