Assign/access bus data using variable index (Simulink)

9 次查看(过去 30 天)
Hello,
I'd like to access/assign bus data, but using a variable index rather than the bus component name. The code is written in a MATLAB function block in Simulink.
For example:
function y = fcn(idx, data)
%#codegen
y.bus_data_1 = data;
should be replaced with something like
function y = fcn(idx, data)
%#codegen
y.{idx} = data;
only I can't find the correct synthax. Does anyone know how to solve it?
(I could transform the bus into a vector, use the vector when assigning data, then create a new bus, but there should be an easier, better way)

回答(1 个)

Kaustubha Govind
Kaustubha Govind 2012-4-18
Not sure if I've understood your question correctly, but I think what you'd like to do is done in MATLAB using:
y = struct('a',1,'b',9,'c',10);
fldnms = fieldnames(y);
y.(fldnms{idx}) = 3
In the MATLAB Function block, you will need to "pre-allocate" y to some default structure that matches the bus type that you have selected as the output datatype. Then, you might be able to access the desired field index by using the last two lines of the above code, but it looks like fieldnames is not supported for code generation. So you might need to put the last two lines in a separate function that you call from your MATLAB Function block using the coder.extrinsic directive.
  2 个评论
JGun
JGun 2012-4-18
You understood me just fine! I know I have to 'pre-allocate' y, I left that out in the example for clarity. However, I think I will need to generate code from the model at some point, and using coder.extrinsic excludes that part of the code as far as I can recall?
Kaustubha Govind
Kaustubha Govind 2012-4-18
JGun: Yes, using coder.extrinsic excludes that function from code generation. Unfortunately, I don't think you can dynamically access structure fields for code generation. See "Do not reference fields dynamically" on http://www.mathworks.com/help/releases/R2011a/toolbox/eml/ug/bq1h2z9-72.html

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Event Functions 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by