This note explains how custom C or MATLAB code can be integrated into a Simulink or PLECS model to implement advanced algorithms that can be complex to develop with the graphical approach. It covers:

  • C code on Simulink (S-Functions)

  • MATLAB code on Simulink

  • C code on PLECS

C code on Simulink (S-Functions)

The best way to include C code into a Simulink model is by using S-functions. With S-functions, users can basically create a custom Simulink block, whose behavior is defined by code (C, C++, Fortran or MATLAB). The block can then be used in both Simulation and Code Generation modes of ACG SDK.

Creating an S-function

Simulink provides an S-function Builder block that generates the necessary files and helps define the inputs, outputs and parameters of the S-function.

The inputs, outputs and parameters can be defined in the Data Properties tab:

Then, your C code can be written in the Outputs tab.

Finally, the following build options can be configured in the Build Info tab:

When finished, the Build button on the top right corner generates the necessary files. These include:


Is the S-function files that define the function inputs, outputs and parameters and call the wrapper function.


Is a function that contains the user-written code of the S-function. This file is the only file compiled by the imperix toolchain in code generation.


Is an interface defining how the code should be called by Simulink Coder.


Is the compiled version of the S-function.

Make sure that MATLAB is in the same folder as your model when you click the Build button. This ensures that the generated files will have the same path as your model and that the compiler will be able to find them when generating code for the whole model.

A MEX compiler is required to use S-functions. If none is installed, please follow the instructions of the section “Mex compiler add-on” from PN133: Installation guide for imperix ACG SDK.

Using the S-function

The S-Function Builder block also serves as a wrapper for the generated S-function, which means that it can be used inside a model as any other Simulink block. Alternatively, an S-function block can be used to integrate the generated files into a Simulink model.

MATLAB code on Simulink

As seen previously, S-functions can integrate MATLAB code, but for simple codes, Simulink provides a MATLAB function block that is even easier to use.

When double-clicking on a MATLAB function block, the editor opens and the output code of the function can be written directly.

C code on PLECS

PLECS provides a handy C-Script block that lets you write and compile custom C code to integrate it in your model. It works in both simulation and code generation modes.

  • No labels