persistent variable from previous run is not deleted during a new run of my .m file

Here is how my program is structured in a .m file:
clear function_name;
clear all;
clc;
close all;
...
for i = ...
...
ret_val = function_name(...) # function call
...
end
...
function ret_val = function_name(...)
...
persistent persistent_var
...
if( isempty(persistent_var) )
persistent_var = 1
end
...
end
I rubn the program loading this m file in editor and pressing F5. The first run works as expected but on the subsequent runs persistent_var is not empty, and seems to be retained from the previous run. Only way sure fire way I have found to delete it is by executing "clear all" in the command window before running my .m file. Nothing else deletes persistent_var from the previous run.
  1. What is the proper way to delete persistent variables between program executions? I need this variable to not exist during the first call to the functon in my program.
  2. What is the proper way to do this in matlab? I need somethign equivalent to C static variables, so that I can detect the first call to function_name() during my program run and perform a specific task inside it, which should not be performed during later calls to the function.

Réponses (2)

Stephen23
Stephen23 le 28 Avr 2026
Modifié(e) : Stephen23 le 28 Avr 2026
MATLAB is not C. The tidiest way to avoid that ugliness is to use nested functions:
Using nested function avoids this whole problem by design, rather than attempting to "fix" it afterwards with ever larger hammers.
function mainfun()
some_var = 1;
...
for ii = 1:Inf
...
ret_val = nested_fun(..);
...
end
...
function ret_val = nested_fun(...)
...
some_var
...
end
end

Catégories

En savoir plus sur Function Creation dans Centre d'aide et File Exchange

Produits

Version

R2021b

Question posée :

le 28 Avr 2026

Modifié(e) :

le 28 Avr 2026

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by