title: How do I iterate through a struct in an Embedded Matlab Function in Simulink?
body: <p>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:</p>
  
  <pre><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));
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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.</p>