MATLAB Answers

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

93 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

  0 Comments

Sign in to comment.

More Answers (1)

Tuncay  ÖLÇER
Tuncay ÖLÇER on 25 Apr 2019
Edited: Tuncay ÖLÇER on 1 May 2019
The answer is amazingly good! I think this is very important such that, Mathworks should add this "struct2bus" (and possibly the opposite "bus2struct") function as a built-in command to its library in an extended version. It is really important and necessery for being able to use the Simulink as a programming tool in coder environment.

  0 Comments

Sign in to comment.

Sign in to answer this question.