Including MATLAB code in a simulation
By Guy Rouleau
Some algorithms are easier to implement using MATLAB code than blocks. This is why multiple User Defined Function blocks are available in Simulink. But when time comes to implement MATLAB code in a Simulink model, how do you choose one?
I often see users making their life complicated because they choose the wrong block to implement MATLAB code. So today I want to share the process I follow to choose one block over another.
1: Look at the doc
The most important recommendation I can give is to look at the Simulink documentation section titled Comparison of Custom Block Functionality. This documentation page compares all the options and helps choosing the most appropriate based on your requirements.
2: Determine if you need to generate code for the model
If you need to generate code for your model, there are 2 options:
If you don't need to generate code, you have 2 additional options:
Choosing among those brings me to a third piece of advice.
3: Keep it simple
If my algorithm can be implemented in one line using the subset of functions supported by the Fcn block, I use it. This block is designed for simple mathematics expressions. It runs fast and can generate code. I personally use it when I have trigonometric or logical expressions to implement.
The second option on my list is the MATLAB Fcn. To be honest, I almost never use this block. As the documentation for this block says, consider using the Fcn block or a Level 2 M-file S-function instead.
If my algorithm is more complex, but does not have memory or states (the outputs depend only on the inputs), I will consider the Embedded MATLAB Function block.
This block generates code for a library of more that 300 MATLAB functions. It can be configured to accept as many inputs and outputs as needed. Signals connected to it can be of any dimensions and data type, including buses. There is a little overhead the first time you update the model because it generates a MEX-file, but once it is compiled it runs fast.
Sometimes I need my MATLAB code to interact closely with the Simulink solver. In this case, I go for an S-function, typically a Level-2 MATLAB-File S-Function. The S-function API allows you to interact closely with the Simulink solver and implementing everything the Simulink shipping blocks do.
I have to admit that for a long time I was scared by S-functions because I thought they were too complex. Now, I realize I don't have to start from scratch. I usually adapt one of the existing demo S-functions to meet my needs. When I need an S-function, I type sfundemos at the MATLAB command prompt to open a library of examples.
Now it's your turn
What is your preferred way to implement MATLAB code in a simulation? Share how you choose your implementation and leave a comment here.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.