MATLAB Answers


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

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?


Log in to comment.

1 Answer

Answer by Lars Reimer on 15 Nov 2012
 Accepted Answer


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.

  1 Comment

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.

Log in to comment.

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today