## Static array with a size determined by paramter in a S-function

Asked by Lars Reimer

### Lars Reimer (view profile)

on 14 Nov 2012
Accepted Answer by Lars Reimer

### Lars Reimer (view profile)

Hello everybody,

I am currently working on a discrete version of a S-function in order to make the execution process quicker (fixed step solver instead of ode1 or so).

For this I need to eliminate all derivatives in the function. Normally this is possible by allocating a static variable and reading out the current step size to determine the value change per step size.

But in this case I need to do this for an array of values and additionally the size is not fixed but determined by a parameter. So it's not possible to declare the array before the #define statements, because there is the parameter unknown yet.

I know it's possible to define Inputs, Outputs and Parameters with so far not known array size, so could I use sth like Rwork for this issue? And if yes, how does it work then?

## Products

### Lars Reimer (view profile)

Answer by Lars Reimer

### Lars Reimer (view profile)

on 15 Nov 2012

OK,

solved it myself already. An easy way is to declare a pointer with "static double *Pointername" at the S-function Top before all the #defines.

Then the size can be determined by a parameter in the Initialize function with: "Pointername = malloc (Parametername * sizeof (double));"

And with that, S-functions can calculate arrays of derivatives without using the derivative function -> Fixed step Discrete Solver (which is quicker than ode1)can be used.

Kaustubha Govind

### Kaustubha Govind (view profile)

on 19 Nov 2012

Lars: Thanks for posting your solution. Just as a cautionary word, static variables in S-function are not instance-specific. However, if you're only using the variable as a kind of global data store, it should be ok. If you need instance-specific persistent data, you need to use some type of work vector, whose size can be specified based on a parameter value in mdlSetWorkWidths.

#### Join the 15-year community celebration.

Play games and win prizes!

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