How to Use Persistent Variable in MATLAB: Syntax and Examples
In MATLAB, use the
persistent keyword inside a function to declare a variable that keeps its value between calls. Unlike regular variables, persistent variables do not reset every time the function runs, allowing you to store data across multiple calls.Syntax
The persistent keyword declares a variable inside a function that retains its value between calls. You write persistent varName at the start of the function. If the variable is empty, you can initialize it once. This keeps the variable's value until MATLAB clears it or the function is cleared.
matlab
function count = examplePersistent() persistent counter if isempty(counter) counter = 0; % Initialize once end counter = counter + 1; count = counter; end
Example
This example shows a function that counts how many times it has been called using a persistent variable. Each call increases the count by one and returns it.
matlab
function count = callCounter() persistent counter if isempty(counter) counter = 0; % Initialize only once end counter = counter + 1; count = counter; end % Test calls count1 = callCounter(); count2 = callCounter(); count3 = callCounter(); fprintf('Call 1: %d\nCall 2: %d\nCall 3: %d\n', count1, count2, count3);
Output
Call 1: 1
Call 2: 2
Call 3: 3
Common Pitfalls
- Forgetting to check
isemptybefore initializing causes the variable to reset every call. - Persistent variables are local to the function and cannot be accessed outside.
- They keep values until MATLAB or the function is cleared, so unexpected values may persist if not reset manually.
matlab
function count = wrongPersistent() persistent counter counter = 0; % Wrong: resets every call counter = counter + 1; count = counter; end % Correct way: function count = correctPersistent() persistent counter if isempty(counter) counter = 0; % Initialize once end counter = counter + 1; count = counter; end
Quick Reference
Persistent Variable Tips:
- Declare with
persistent varNameinside a function. - Initialize only if
isempty(varName)is true. - Use to store data between function calls without global variables.
- Cleared when MATLAB or function is cleared.
Key Takeaways
Use
persistent inside functions to keep variable values between calls.Always check
isempty before initializing persistent variables to avoid resetting.Persistent variables are local to the function and not accessible outside.
They retain values until MATLAB or the function is cleared.
Use persistent variables to maintain state without using global variables.