tmar89
tmar89

Reputation: 33

How do I iterate through a struct in an Embedded Matlab Function in Simulink?

I have hit a roadblock where I am trying to iterate through a structure formed in the MATLAB workspace inside an EML (Embedded Matlab) function block in SIMULINK. Here is some example code:

% 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 is a Bus type Parameter for the MATLAB Function Block (EML) in SIMULINK. Below is the area I am running into trouble with. I know the number of elements inside my struct and I know the names, but the number of elements can change with any configuration. So I cannot hardcode based on the Element names. I have to iterate through the struct inside the EML block.

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

Any thoughts on how I can iterate through a struct type in SIMULINK? Also, I cannot use any extrinsic functions like num2str because this is to be compiled on a target system.

Upvotes: 1

Views: 1608

Answers (1)

Amro
Amro

Reputation: 124563

I believe you are trying to use dynamic field names for structures. The correct syntax should be:

element = p_Elements.( sprintf('Element%d',i) );
type = element.type;
%# ...

Upvotes: 2

Related Questions