Does it possible to use a function with persistent variables several times?
Show older comments
I want to process several independent data arrays using a function which includes persistent variables in the following manner:
function cnt = example()
persistent cnt_p;
if isempty cnt_p
cnt_p = 0;
end
cnt=cnt_p;
cnt_p=cnt_p+1;
end
A = [1 2 3];
B = [4 5 6];
cnt1 = example(A(1));
cnt2 = example(B(1));
cnt1 = example(A(2));
cnt2 = example(B(2));
.....
Function saves variable cnt_p so result of this code will be: cnt1 = 3; cnt2 = 4;
But I want to see: cnt1 = 2; cnt2 = 2;
P.S. Of course I can simply create several copies of this function but it does not convenient.
Accepted Answer
More Answers (1)
Alessandro Masullo
on 19 Feb 2015
0 votes
If you want to clear the persistent variable you need to do it explicitly:
clear example
1 Comment
Alex Antipin
on 19 Feb 2015
Categories
Find more on Use System Objects in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!