Home Questions What are persistent variables?

What are persistent variables?

DWQA QuestionsCategory: Custom Task DevelopmentWhat are persistent variables?
Koloman Varady Staff asked 6 years ago
What are persistent variables? How do I use them and what is an example of their use?
1 Answers
Koloman Varady Staff answered 6 years ago
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.
Ian Brown Staff replied 5 years ago

For an example Task Program that uses persistent variables, please see the Visuomotor Rotation task that is available for download as a Sample Custom Task