ITKeyword,专注技术干货聚合推荐

注册 | 登录

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

itPublisher 分享于

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1073

2020阿里云最低价产品入口,含代金券(新老用户有优惠),
地址https://www.aliyun.com/minisite/goods

推荐: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)
%#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.

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
1

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

 | 


相关阅读排行


相关内容推荐

最新文章

×

×

请激活账号

为了能正常使用评论、编辑功能及以后陆续为用户提供的其他产品,请激活账号。

您的注册邮箱: 修改

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

如果您没有收到激活邮件,请注意检查垃圾箱。