Is there a way to create a function from a model in Simulink, using Code Generation, so that this function can be used independantly as part of any other code project ?

1 view (last 30 days)
I have a set of blocks in Simulink that implement a particular algorithmic logic. Is there any way that I can generate code for a function that implements this same logic? The function code should be such that I can use it with other parts of any other code project, which are developed outside MATLAB.
Ideally the function code generated should be in files of the form 'myfunc.c' and its accompanying header 'myfunc.h' which I can just easily re-use with other code projects.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Mar 2012
This is possible in Simulink, by encasing the entire set of blocks that represent the algorithmic logic into a sub-system and then using the 'Reusable Function' option for that subsystem.
A Detailed Example:
Find attached a model : "MyExample.mdl" which contains a simple logic implementation. Assume you want a function to be generated for implementing this same logic.
1.) Right click this subsystem and choose 'Subsystem Parameters' to bring up the options dialog box. In the 'Main' Pane make sure you enable 'Treat as atomic unit' option.
2.)Then, in the 'Code Generation' Pane, set the 'Function Packaging' option to 'Reusable Function'. You can also set the 'Function Name' Options based on your preferences. In this example I have set the 'Function Name' to 'MyDemoFunction'.
3.) Now, go to Configuration Parameters and check the options which are enabled/disabled in the Optimizations Pane and also the Code Generation Pane (Real-Time Workshop pane for releases prior to R2011a). These can be tweaked based on your use-case.
4.) The selected target is 'ert.tlc' (ert target generates the cleanest code).
5.) Now hit 'Generate Code' in the main 'Code Generation' Pane and the code should be generated for you. Please notice the two files that get generated for the subsystem - 'MyDemoFunction.c' and 'MyDemoFunction.h' - they contain code that can be used standalone in other parts of your project.
  1 Comment
Sriram Narayanan
Sriram Narayanan on 24 Apr 2015
Edited: MathWorks Support Team on 27 Apr 2023
It is not possible to use variable-sized signals with the "reusable function" interface.
There are no workarounds as far as I can remember, but, please contact MathWorks Technical Support to see if they have a possible workaround to this issue.

Sign in to comment.

More Answers (0)

Categories

Find more on Simulink Coder in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!