How do I create a bus object from a struct in my workspace using Simulink 7.4 (R2009b)?

45 views (last 30 days)
I have a structure with different datatypes in my workspace, which I want to use as a bus in Simulink. For example:
 
myStruct.firstField = [1 2 3];
myStruct.secondField = uint8(17);
myStruct.thirdField = 5;
Now, I want to be able to import this data into Simulink in a bus. I can import my data using constant blocks, which directly refer to fields of the structure and create a bus with these blocks. However, that is a lot of work.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 18 Nov 2016
This can be accomplished by creating a bus object with a script and using an Embedded MATLAB Fcn block in Simulink to output data into this bus.
Here is how this can be done:
  • Attached file createTestStruct.m generates a simple structure, a, in the MATLAB workspace as an example with different datatypes
  • Attached file struct2bus.m generates a Simulink Bus Object based upon the fields and datatypes in the structure
  • Attached file busobject2_ex.mdl is a Simulink model including an Embedded MATLAB Fcn block that uses the data from the structure to feed a bus
In order to run the example:
1. Download the attachments (located at the bottom of the page) in a single directory.
2. Run the file createTestStruct.m to create a test structure.
3. Open and run busobject2_ex.mdl to see the result.
Here is how it works:
  • At initialization of the model the struct2bus function is called to convert the structure to a Bus Object called mybus:
1. Right-click the Embedded MATLAB Fcn block.
2. Select 'Block properties...'
3. Select the 'Callbacks' tab
4. Choose 'InitFcn', which now reads "struct2bus(a,'mybus')"
  • The output of the Embedded MATLAB Fcn block is linked to a Bus Object of type mybus:
1. Open the Embedded MATLAB Fcn block by double clicking it
2. Choose 'Edit Data/Ports' from the Tools menu
3. Select Output port 1
4. Choose 'Type', "Bus: bus object name"
5. Click on the Data type assistant button (>>)
6. Fill out the name of the Bus Object
  • Structures in Embedded MATLAB Fcn blocks are automatically converted to Bus Objects, which property is used in this example

More Answers (0)

Categories

Find more on Simulink Functions in Help Center and File Exchange

Products


Release

R2008b

Community Treasure Hunt

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

Start Hunting!