Initialize Persistent Variables in MATLAB Functions - MATLAB & Simulink (original) (raw)

Main Content

A persistent variable is a local variable in a MATLAB® function that retains its value in memory between calls to the function. If you generate code from your model, you must initialize a persistent variable for your MATLAB functions. For more information, see persistent.

When using MATLAB functions that contain persistent variables in Simulink® models, you should follow these guidelines:

If you do not follow these guidelines, several conditions produce an initialization error:

For example, the function fcn below uses a persistent variable, n. fcn violates both guidelines. The initial value of n depends on the input u and thereturn statement interrupts the normal control flow of the function. Consequently, this code produces an error when used in a model that has one of the conditions described above.

function y = fcn(u) persistent n

if isempty(n)
    n = u;
    y = 1;
    return
end

y = n;
n = n + u; 

end

To prevent the error, initialize the persistent variable by setting it to a constant value and removing the return statement. This modified version offcn initializes the persistent variable without producing an error:

function y = fcn(u) persistent n

if isempty(n)
    n = 1;
end

y = n;
n = n + u; 

end

MATLAB Function Block with No Direct Feedthrough

This model contains a MATLAB Function block that uses the first version of fcn, described previously. The MATLAB Function block input is a square wave, which is provided by a Sign and Sine Wave block. The MATLAB Function block adds the value of u to the persistent variable n at each time step.

Simulate the model. The simulation returns an error because:

Modify the MATLAB Function block code, as shown in the corrected version of fcn. Simulate the model again.

State Control Block in Synchronous Mode

This model contains a MATLAB Function block that uses the first version of fcn, described previously. The MATLAB Function block input is a square wave, which is provided by a Sign and Sine Wave block. The MATLAB Function block adds the value of u to the persistent variable n at each time step. The model contains a State Control block where State control is set to Synchronous.

Simulate the model. The simulation returns an error because:

Modify the MATLAB Function block code, as shown in the corrected version of fcn. Simulate the model again.

Stateflow Chart Implementing Moore Semantics

This model contains a Stateflow chart with a MATLAB function that uses the first version of fcn, described previously.

The MATLAB function adds the value (1 or -1) determined by the active state to the persistent variable n at each time step.

Simulate the model. The simulation returns an error because:

Modify the MATLAB function code, as shown in the corrected version of fcn. Simulate the model again.

See Also

Blocks

Functions

Topics