persistent variable from previous run is not deleted during a new run of my .m file
Show older comments
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.
- 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.
- 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.
Answers (2)
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
Using two .m-files instead of only one script seems to solve the problem according to
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!