Home Examples Persistent Variables
Coding Tips

Persistent Variables

Persistent variables are ones that hold their value between calls to the embedded MATLAB code they are defined in. In the context of a Simulink model this can be an enormously helpful feature in any of the following scenarios:

  • Keeping history for a variable. e.g. Compare the hand speed now to what it was 100 ms ago.
  • Accumulating a score across trials
  • Using the behaviour in one trial to affect the next, e.g. if hand speed was above a threshold in one trial, apply a higher viscous load in the next trial

10.27.1      Persistent Variable Examples

Persistent variables are always used in the context of embedded MATLAB functions in Simulink (though they also work in MATLAB code run at the MATLAB prompt).

Below is the standard way to declare and initialize a persistent variable. The variables do not need to be initialized to zero specifically.

function persistent_test()

% separate variable names with a space 
persistent my_variable1 my_variable2

if isempty(my_variable1) 
  my_variable1 = 0;
  my_variable2 = 0; end

A common usage for persistent variables is to keep track of kinematic values as a task progresses. There are 2 phases to starting a task: starting the model and starting the task to collect data. During the initial phase it can be normal for some kinematics to not be fully initialized yet. As such, it’s often helpful to wait until kinematics are initialized before storing them in persistent variables.

The Simulink code for setting up a persistent variable with valid kinematics looks like:

Figure 10.37: Simulink code for setting initializing a persistent variable

The Embedded MATLAB code for the example looks like:

function y = fcn(hand_velocity, task_is_running) 
persistent previous_hand_velocity
if isempty(previous_hand_velocity) && task_is_running 
  previous_hand_velocity = hand_velocity;

Related Tasks

Coding Tips
Custom Control of the Trial Protocol Order
Normally, Dexterit-E manages and controls the order in which Trial Protocols (TPs) execute based on what is defined in the block table of the Task Protocol (see the Dexterit-E User Guide for more details).
Coding Tips
Show Time Remaining in a Task
If your task runs for a known (or calculable) amount of time, then it is possible to display the amount of time remaining in Dexterit-E.