# Including MATLAB code in a simulation 26

Posted by **Seth Popinchalk**,

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.

**Category:**- MATLAB,
- Simulink Tips

## 26 CommentsOldest to Newest

**1**of 26

Guy,

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.

Regards

Rob

Toongabbie

Vic Aust

**2**of 26

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.

**3**of 26

Good morning,

I’m interested by using Matlab programming and simulink,

Ineed some sites to learn

Tkankyou

**4**of 26

thanks,great article,so much detail,keep them coming.

**5**of 26

Guy,

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.

Sean

**6**of 26

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.

Thanks

Guy

**7**of 26

Seth/Guy,

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!

Paul

**8**of 26

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:

http://www.mathworks.com/support/solutions/en/data/1-77XNEW/index.html

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.

**9**of 26

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).

**10**of 26

Hi Seth,

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

**11**of 26

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

**12**of 26

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

**13**of 26

@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.

**14**of 26

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?

**15**of 26

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

x=linspace(0,100,1000);

y=sin(x);

plot(x,y)

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

function z = sinewave

eml.extrinsic(‘plot’);

% x axis reference

x = linspace(0,0.16,400);

y = linspace(0,2*pi,400);

% y axis calculation

z = sin(8*y);

%plotting wave

plot(x,z);

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

**16**of 26

@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.

**17**of 26

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!!

Thanks

TK

**18**of 26

@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.

**19**of 26

hi sir,

thanks for your response to my question dated on 2nd october.

my main aim is to use matlab coding.in 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.

**20**of 26

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

**21**of 26

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.

**22**of 26

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

Thanks in advance.

**23**of 26

Hi,

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

Plz reply urgently

**24**of 26

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.

**25**of 26

how to implement this equations in simulink block model

1)(-(m*a)/F)

2)(a*(1-(V-((V*R)*R))/V)-(R*(a*R))))/V

it is showing syntax error whenever i run the block

**26**of 26

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

## Recent Comments