This example shows how to use structures in a MATLAB Function block to read and write to Simulink® bus signals.

In this model, a MATLAB Function block receives a bus signal using the structure inbus at input port 1. The block outputs two bus signals: structure outbus at output port 1 and structure outbus1 at output port 2. The input signal comes from the Bus Creator block MainBusCreator, which bundles signals ele1, ele2, and ele3. The signal ele3 is the output of another Bus Creator block SubBusCreator, which bundles the signals a1 and a2. The structures outbus and outbus1 connect to Bus Selector blocks that, in turn, connect to Display blocks.
To explore the MATLAB function fcn, double-click the MATLAB Function block. Notice that the code implicitly defines a local structure variable mystruct using the struct function, and uses this local structure variable to initialize the value of the first output, outbus. It initializes the second output, outbus1, to the value of field ele3 of structure inbus.
Here are the definitions of the structures in the MATLAB Function block in the example, as they appear in the Ports and Data Manager:

Each structure input and output must be defined by a Simulink.Bus
object in the base workspace (see Create Structures in MATLAB Function Blocks). This means
that the structure shares the same properties as the bus object, including number, name,
type, and sequence of fields. In this example, the following bus objects define the
structure inputs and outputs:

The Simulink.Bus object MainBus defines structure
input inbus and structure output outbus. The
Simulink.Bus object SubBus defines structure output
outbus1. Based on these definitions, inbus and
outbus have the same properties as MainBus and,
therefore, reference their fields by the same names as the fields in
MainBus, using dot notation (see Index Substructures and Fields). Similarly, outbus1
references its fields by the same names as the fields in SubBus. Here are
the field references for each structure in this example:
| Structure | First Field | Second Field | Third Field |
|---|---|---|---|
inbus | inbus.ele1 | inbus.ele2 | inbus.ele3 |
outbus | outbus.ele1 | outbus.ele2 | outbus.ele3 |
outbus1 | outbus1.a1 | outbus1.a2 | — |