What are persistent variables? How do I use them and what is an example of their use?
Persistent variables in a function will preserve their state between function calls. For Simulink, this means that the values will be preserved from one time-step to the next. An example of using a persistent variable is storing a target's position so you can change it dynamically throughout a task. To use a persistent variable, you need to define it as persistent and you need to initialize it. Care must be taken to initialize it to the correct size (i.e. the size that it will be used in that function). The isempty(x) function can be used to check whether the variable x is initialized, and if it is not initialized, then you can use that opportunity to set the persistent variable to an initial value. In this way, you can make sure that the variable is initialized when the task is loaded and only initialized once. For example, if x needs to be a persistent 2x10 array, then the following code will define it as persistent, and initialize it to the correct size: persistent x; if isempty(x) x = zeros(2,10); end Note: you cannot pass in a variable (e.g. from the task protocol tables) to initialize the persistent variable. The initialization requires a constant value for initial value because input variables are not always available when the task is first loaded.
Please login or Register to submit your answer