Does it possible to use a function with persistent variables several times?
Ältere Kommentare anzeigen
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.
Akzeptierte Antwort
Weitere Antworten (1)
Alessandro Masullo
am 19 Feb. 2015
0 Stimmen
If you want to clear the persistent variable you need to do it explicitly:
clear example
1 Kommentar
Alex Antipin
am 19 Feb. 2015
Kategorien
Mehr zu Use System Objects finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!