MATLAB Examples

Persistent Example

This example demonstrates how to use persistent variables when loading data in a function. Doing things this way guarantees that the "data" value in persistentFunction is only loaded or changed when necessary.

Note that, I have a hunch that MATLAB may actually recognize a function is called repeatedly loading a mat file when not using persistent. It may do a form of what "persistentFunction" does with not loading the mat file implicitly. If know for sure about this behavior, please inform me.

Contents

persistentFunction Code

function output = persistentFunction(input)
% persistentFunction loads data between calls and changes it when the input
% changes.

persistent data inputPrevious

% - Check if this is the first time the function is called.
% - If it isn't the first time, check if the input has changed.
if isempty(inputPrevious) || inputPrevious~=input
    switch input
        case 1
            fprintf('file1.mat loaded.\n');
            d = load('file1.mat');
            data = d.c;
        case 2
            fprintf('file2.mat loaded.\n');
            d = load('file2.mat');
            data = d.c;
        otherwise
            % 99% of the time you should use an otherwise statement to
            % handle ways you didn't intend to call this function. This
            % will help catch bugs when you do something you didn't intend
            % to do.
            error('Input value not valid. No file loaded.');
    end
    % save the input last so that an error is thrown if a bad input value is
    % passed in. We do not save the bad input into inputPrevious.
    inputPrevious = input;
else
    fprintf('No file loaded on this call.\n');
end

% pass data to the output just for demonstration purposes
output = data;


end

Prepare workspace and command line

clc;
clear all; %#ok<CLALL> % clears the persistent variables. Be careful with this!!!

call persistentFunction the first time

persistentFunction(1)
file1.mat loaded.

ans =

     1

call persistentFunction again with the same value

persistentFunction(1)
No file loaded on this call.

ans =

     1

call persistentFunction and change the value

persistentFunction(2)
file2.mat loaded.

ans =

     2

call persistentFunction and change the value

persistentFunction(1)
file1.mat loaded.

ans =

     1

call persistentFunction and change the value

persistentFunction(2)
file2.mat loaded.

ans =

     2

call persistentFunction again with the same value

persistentFunction(2)
No file loaded on this call.

ans =

     2

call persistentFunction with a bad input value

try
    persistentFunction(3)
catch me
    % turn the error to a warning
    warning(me.message);
end
Warning: Input value not valid. No file loaded. 

call persistentFunction again with the same value that last worked

persistentFunction(2)
No file loaded on this call.

ans =

     2