MATLAB Answers


Represent Simulink Integrator block as Matlab Function

Asked by River Rock on 4 Dec 2012


I need to implement the following behavior :

The Integrator and my_Integrator blocks have to be equivalent I/O.

How should I write the Matlab Function ?

Thanks for any reply.

5 Answers

Answer by Ryan G
on 4 Dec 2012
 Accepted Answer

As this looks like a homework problem, I can't answer directly. However I will point you in the direction of persistent variables.


Log in to comment.

Answer by Azzi Abdelmalek
on 7 Dec 2012
Edited by Azzi Abdelmalek
on 8 Dec 2012

I don't know why do you need this, maybe if you explain exactly what you need, there is better way


The solution it's already posted above. But since you and Guy disapprove this, I am waiting for the better solution.

I didn't need any clock input , please see

And even if I did, I guess it could have been fetched using the get_param command (never tried this though)

Ok, I see, If T is constant, you must then set, in model configuration parameters your fixed step time to T, and also your step block sample time to T. In this case you don't need a clock.

function y = fcn(u)
persistent   uold yold
if isempty(uold)
y = u*T+yold-(u-uold)*T/2

Changing the sample time of the Step block to 0.01 removed the previous offset. Thanks

Log in to comment.

Answer by Guy Rouleau
on 5 Dec 2012

This is not a good idea. The MATLAB function is not designed for this purpose.


Log in to comment.

Answer by River Rock on 5 Dec 2012
Edited by River Rock on 6 Dec 2012

My main goal is to implement the differential equations of a physical system using a single Matlab Function. As the sums and gains were easy to represent, I couldn't find any alternative for the integration.


Show 1 older comment

Your idea would be to declare a persistent variable for the numeric integration ?

Y(s) = U(s) / s => y(z) = yOld + u(z)

so you declare persistent x = y to stand for yOld ?

Can I avoid this low-level arithmetic and call a predefined method instead (ode45 for example) ?

What you have written is close it would be more like:

y(z) = yOld+u(z)/SampleTime

You cannot use the ODE solver in the MATLAB function block.

Any idea on how to get rid of this offset ?

Code looks like:

function y = fcn(u)
persistent yOld;
persistent uOld;
if (isempty(yOld))
    yOld = 0;
if (isempty(uOld))
    uOld = 0;
y = yOld + (T/2)* (u + uOld);
%y=yOld + u*T;
yOld = y;
uOld = u;

Log in to comment.

Answer by River Rock on 5 Dec 2012

Can anybody suggest a better way of implementing the numerical integration ? The code has to be written inside the Matlab Function Block though.


Log in to comment.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!