Guy on Simulink

Simulink & Model-Based Design

Including MATLAB code in a simulation 27

Posted by Seth Popinchalk,

Blogger, Guy Rouleau 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.

Fcn block

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.

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.

Level 2 MATLAB File S-Function

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.

27 CommentsOldest to Newest

Rob Garnett replied on : 1 of 27


I think you are spot on.

Fcn Blocks, then embedded, then S Functions.

I find S Functions tricky, but like you I use templates. I certainly wouldn’t start one from scratch.

We have an ABB Infi 90 control system and model the blocks using S Functions for engineering development. We also used S Functions to model Siemens PLC blocks on a complex coal drying/briquetting plant. I did the controls model in S Functions (discrete) and others did the plant model. They used Fcn blocks and ordinary blocks. I then integrated the two parts. I was able to tune the model and then the commissioning team used the P&ID settings and feed forward settings on the real plant.

Not easy for a coal drying and briquetting process with three different fuels.


Vic Aust

James Myatt replied on : 2 of 27

All the MATLAB options are banned in our simulator mainly due to the impact on simulation speed, as well as the need to generate code, so we use exclusively EML and C MEX S-functions.

Lamine Fradi replied on : 3 of 27

Good morning,
I’m interested by using Matlab programming and simulink,
Ineed some sites to learn

Sean Little replied on : 5 of 27


I am a little confused by your comment when you say that you only use an EML block when you do not need states. Using the PERSISTENT keyword works fine, and allows an EML function to model states. Can you elaborate on this?

I have yet to encounter a situation where I need to run Matlab code where an EML block does not work fine. But then, I hardly ever do continuous modeling. Can you provide an example where an EML block would not work? I was a little unclear about this in the documentation also.


Guy replied on : 6 of 27

Hi Sean,

Thank you for bringing that up. I was hoping to receive this question!

You are right when you mention that the PERSISTENT keyword can be used to implement something similar to states for discrete systems. However the Simulink solver does not register the persistent variables as states, which can cause two possible issues:

1. If you compare the types of DWork Vectors for an S-Function, you will see that an S-Function can have both persistent variables and discrete states. The DWork vectors marked as discrete states have the advantage of begin taken into account during linearization and be available for state logging.

2. By default the EML block inherits his sample time. You can initially design a counter (for example, “tmp = tmp+1”) in a discrete EML block, and get the results you expect. In the future someone might reuse your block with a continuous solver. The same counter will then count by steps of 3 for the ode3 solver and steps of 5 for ode5 solver, because continuous solvers take minor time steps not seen by the user. I always try to discourage practices which can lead to significantly different results for different solvers.

If you are comfortable with these two items, fell free to use the PERSISTENT keyword to implement discrete states in your model. You can find some of the demos doing that and the Simulink HDL Coder mentions this technique in its documentation.

I hope this clarifies my previous post.



Paul J. replied on : 7 of 27


1. Thanks for pointing out that code can be generated for the fcn block. I was unaware of that. Would it be useful to include that information in the Characteristics table at the bottom of the doc page for each block, i.e., whether or not code can be generated for the block? As an aside, there seems to be inconsistency in what the table includes for different blocks. For example the table for the Discrete Derivative seems rather sparse compared to other blocks.

2. I use EMF blocks the same way as you, i.e. no memory or states, direct feedthrough only. If I want to use the EMF block to implement difference equations, I send the output from the EMF block into unit delays on the outside, and then loop the output of the unit delays back around to the input of the block, which I think makes it clear to the user what’s going on.

3. As far as EMF blocks calling other m-files, my understanding is as follows (based on 2009a, my apologies if I’m too far behind) . Suppose an EMF block needs to call the m-function myfunc:

IF myfunc is EML compatible AND myfunc.m includes %#eml

THEN code will be generated for myfunc AND there is no need to declare myfunc as EML.Extrinsic.

ELSE myfunc must be declared EML.Extrinsic AND code will not be generated for myfunc (it will run in the ML interpreter).

Is this correct? I have found this feature very useful for calling my own EML compatible m-functions and not worrying about runtime slowdown. If code is generated for myfunc, will Simulink detect if myfunc.m has changed since the last time code was generated for the EMF block? I could check this myself I suppose, but I don’t have access to ML at the moment.

Thanks for your posts!


Guy replied on : 8 of 27

Hi Paul,

Thank you for the comments!

1. I agree with you that the Characteristics table is different for each block and could be more consistent. Adding an item to mention if the block supports code generation is a good idea, I will forward that to our documentation team.

Currently, a good place to see if a block supports code generation is the Block Support Table.

2. I really like this practice. As you mention it makes it obvious that the EML block has states. I created the following technical solution a few years ago to illustrate how to do something similar for continuous states:

3. Your description is correct. It is possible to call functions located in other MATLAB files from the EML block. Code will be generated if the files are EML compatible and have the %#eml keyword. The EML.EXTRINSIC keyword must be used if the files are not EML compatible and the MATLAB interpreter will be used.

When a change is made to a MATLAB file, the EML block will notice it and rebuild automatically.

KMR replied on : 9 of 27

My group forbids the use of the fcn block because (a) its syntax is error-prone (quick, how many times have you used the wrong index for u in the block), and (b) we’ve had some subtle code generation problems with it (which may or may not have been reported due to the difficulty of assembling a reproducible, non-ITAR test case). We mandate eML for this kind of stuff.

And one way of getting around the lack of true states in eML is to break up the eML into one block that computes and outputs the derivatives, connected to a Integrator block, and then sending the output of the integrator into another eML script to process the states. A bit cumbersome but may do in a pinch, at least until the Mathworks allows writing S-functions directly in eML (similar to the BlockScript capability in MATRIXx).

Tom Erkkinen replied on : 10 of 27

Hi Seth,

We have a new API that automates plotting and comparing numerical differences between simulation and generated code (SIL or PIL).

wei replied on : 11 of 27

Hi Tom, These slides supplement release note nicely. Other SL/SF products have them as well. Could TMW make them easy to find?

Seth replied on : 12 of 27

@wei – Right now, I think only Simulink, Real-Time Workshop, Embedded Coder, EDA Link and Stateflow have feature slides. If the product has slides, you will find a link to “Highlights and screen shots” in the Latest Features section:

Feature slides are under highlights and screen shots

wei replied on : 13 of 27

@Seth, Thank you for this revelation. I am not able to upgrade on every new releases. It would be nice, like old release notes, if older highlights are easily available.

Secondly, the release notes are part of document and a few clicks away from Overview tab shown above. It could be more convenient if highlight and release note are next to each other.

Omar Gomez replied on : 14 of 27

hey greetings!!

I wonder if you could tell me if there is something like the Real-Time Windows Target for Linux, and if there is nothing that resembles, what may be the most similar to the functions provided by the Real-Time Windows Target?

murali krishna replied on : 15 of 27

Hi sir,
I would like to use embedded matlab function.
i had generated sine wave in matlab coding now the problem is i am getting sine wave as output in m file(matlab coding file)using plot command.but using embedded matlab function i am not getting sine wave as output of embedded matlab function (or input to scope).can plz told to me how to get sine wave at scope.
thanking you.plz reply sir

below is the code for sine wave in m file

code to get sine wave in emebbeed matlab function(problem i am facing)

function z = sinewave
% x axis reference
x = linspace(0,0.16,400);
y = linspace(0,2*pi,400);
% y axis calculation
z = sin(8*y);
%plotting wave

so the generated wave using Embedded matlab function(using plot command in programme) is to go to scope.plz tell the solution sir.

Seth Popinchalk replied on : 16 of 27

@Omar Gomez – a pseudo real-time target can be created on Linux by scheduling the execution of your code. In general, the right way to do this depends a lot on what you are trying to accomplish. Have you ever run you model in external mode with RTW GRT Target?

@murali krishna – If you goal is to get a signal with a Sine wave, I suggest using the Sin block from the sources library. For plotting in Simulink, we use the Scope Block. To start, I suggest you connect the Sine to the Scope and simulate to see you result. Good luck.

TK replied on : 17 of 27

Hello sir,

Iam entering “help mcc” in my command window but the result is `mcc not found`…(Hence iam not able to use ‘mcc’)

What is the possible reason for this…can anyone help please!!


Seth Popinchalk replied on : 18 of 27

@TK – I’m not sure why you selected this post to ask this question. In the future, you might be better served by going to the MATLAB newsgroup with your technical support questions. It seems that you do not have the MATLAB Compiler installed.

murali krishna replied on : 19 of 27

hi sir,
thanks for your response to my question dated on 2nd october.
my main aim is to use matlab matlab coding i had generated the wave using plot command,problem is i have to transfer that plotted wave to simulink to input for other blocks
(plotted wave in coding is an input to one of the simulink block)
.please help me sir.

Zarah Sooruth replied on : 20 of 27

Hello Sir,
I am using embedded matlab functions with 3 phase voltages as input, my aim is to convert them into alpha-beta coordinates, my problem is I dont get any kind of wave when viewed using scope but only step outputs,
please help me sir

Anirudh replied on : 21 of 27

How do I ensure that both embedded M and S-function use the same value of time? I have a Simulink model which contains an embedded M version and an s-function version of an HVAC system. The s-function was compiled in VC++ 2008, and then added to MATLAB.

nilesh chandraker replied on : 22 of 27

please suggest embedded matlab code of linspace which has 3 i want to generate a vector using embedded matlab function block in simulink.
Thanks in advance.

NIles replied on : 23 of 27

Plz suggest some tools to check created model is according to MISRA SL/SF(simulink and stateflow)guidelines or not.
Plz reply urgently

KE replied on : 24 of 27

This overview is still useful if you know the changes to block names since R2011a:
1) Old MATLAB Function block is now Interpreted MATLAB Block.
2) Old Embedded MATLAB Function Block is now MATLAB Function block.

manosh jyoti das replied on : 25 of 27

how to implement this equations in simulink block model
it is showing syntax error whenever i run the block

JUBAIR replied on : 26 of 27

can u please send me a fso simulation model using simulink. i m realy stuck with it,pls help me

aimad replied on : 27 of 27

Mr Guy
Francly, I find too much difficulties in using function block to implement M-code in simulink model.
actually, I want to generate a random carrier (random triangular to genrate random pwm) by using simulink but it is difficult so I have an algorithme that run well. Can you help me to solve this problem.

Add A Comment

What is 3 + 9?

Preview: hide