注册 | 登录

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

itPublisher 分享于



推荐:Define the input/output port name for the Inlined C++ S-function block in Matlab Simulink

DO IT by the Mask option of the context menu of the block by right-click mouse button. and input the text like   disp('Metropolis Hastings/n(MH) sampl

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)
persistent p_Elements; 

% Assign the variable and make persistent on first run
if isempty(p_Elements)
    p_Elements = MyElements;    

% 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;
       output(i) = -1;

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.

matlab struct simulink matlab-coder xpc
  this question
edited Jun 2 '14 at 14:57 Ryan Livingston 1,318 5 15 asked Oct 28 '11 at 15:28 tmar89 18 6


1 Answers

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;
%# ...

  this answer
edited Apr 3 '13 at 12:19 answered Oct 29 '11 at 12:23 Amro 107k 19 180 323









您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱