This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English verison of the page.

Note: This page has been translated by MathWorks. Please click here
To view all translated materals including this page, select Japan from the country navigator on the bottom of this page.

Working with Persistent Variables

This example shows how to generate a MEX function from a MATLAB function, 'compute_average', that uses persistent variables. It illustrates that you must clear the state of persistent variables before using the function to compute the average of a new set of values.


There are no prerequisites for this example.

Create a New Folder and Copy Relevant Files

The following code will create a folder in your current working folder (pwd). The new folder will only contain the files that are relevant for this example. If you do not want to affect the current folder (or if you cannot generate files in this folder), you should change your working folder.

Run Command: Create a New Folder and Copy Relevant Files


About the 'compute_average' Function

The compute_average.m use two persistent variables, the accumulated sum and the number of values added so far, so that you can call the function with one value at a time.

type compute_average
% y = compute_average(x)
% This function takes an input scalar value 'x' and returns the average
% value so far.
function y = compute_average(x) %#codegen
assert(isa(x,'double')); % Input is scalar double

% Declare two persistent variables 'sum' and 'cnt'.
persistent sum cnt;

% Upon the first call we need to initialize the variables.
if isempty(sum)
    sum = 0;
    cnt = 0;

% Compute the accumulated sum and the number of values so far.
sum = sum + x;
cnt = cnt + 1;

% Return the current average.
y = sum / cnt;

The %#codegen directive indicates that the MATLAB code is intended for code generation.

Generate the MEX Function

First, generate a MEX function using the command codegen followed by the name of the MATLAB file to compile.

codegen compute_average

By default, 'codegen' generates a MEX function named 'hello_world_mex' in the current folder. This allows you to test the MATLAB code and MEX function and compare the results.

Run the MEX Function

(10 + 20 + 100) / 3 = 43.3333

ans =


ans =


ans =


Clear the Internal State of Persistent Variables

Clear the persistent variables by using the 'clear mex' command.

clear mex

Run the MEX Function Again to Calculate the Average of a Different Set of Values

(10 + 20 + 30 + 40) / 4 = 25

ans =


ans =


ans =


ans =



Remove files and return to original folder

Run Command: Cleanup

Was this topic helpful?