Assign/access bus data using variable index (Simulink)

14 views (last 30 days)
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)

Answers (1)

Kaustubha Govind
Kaustubha Govind on 18 Apr 2012
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 Comments
JGun
JGun on 18 Apr 2012
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 on 18 Apr 2012
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

Sign in to comment.

Categories

Find more on Event Functions in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!