Guy on Simulink

Simulink & Model-Based Design

For Each Subsystem and Code Generation

Today Guy Rouleau is back to introduce the code generated from the For Each Subsystem.

Code generator, Guy Rouleau

I created an example model implementing the same functionality as in my previous post, but using Stateflow. I like using Stateflow to create behavioral models when I am most interested in expressing the input-output relationship of the system.

Modulo-4 Counter Using Stateflow

I placed the chart in a For Each Subsystem.

Stateflow chart inside a For Each Subsystem

To make the code clearer for this post, I configured the Stateflow chart to generate a Reusable Function in a separate file.

Configuring the Stateflow chart to be a reusable subsystem

Let's now look at the generated code:

Copying the inputs into a contiguous vector
Click image to enlarge.

I added colors to highlight the different parts of the code. In the first part (green), notice that the components of the input signal are placed in contiguous locations in memory. The For Each Subsystem needs this step if the input is not already contiguous. Note that this step respects the optimization settings like Loop unrolling threshold and Use memcpy for vector assignment

Inside the FOR loop, a set of structures are used to store signals and states required by each instance of the subsystem. These structures are passed to the reusable Stateflow chart function. When the loop is completed, each element of the output signal is assigned to its destination.

Reusable Code

As pointed out by my colleague Parasar Kodati, the For Each Subsystem can generate reusable code. Let's say I have multiple instances of this same For Each Subsystem in a model, all with a different number of iterations.

Multiple instances of For Each Subsystems

I configure all the For Each Subsystems to generate a reusable function with the same function name and file name. Now the FOR loop is located in a separate function, which take as input the number of iterations.

Multiple instances of For Each Subsystems
Click image to enlarge.

Notice that I used different vector lengths to highlight how the inputs and outputs to the For Each Subsystem are handled by the Loop unrolling threshold and Use memcpy for vector assignment options.

Now it's your turn

Are you already using the For Each subsystem? Leave a comment here and tell us what you are using it for.

|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.