MATLAB: 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

codefunctionindependantreusablesimulink coderstandalone

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.

Best Answer

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.