how to intialize a variable only once?the below written code should execute only once.later the value must b retained. how it is done
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
rashmi am
el 28 de Feb. de 2015
Comentada: rashmi am
el 3 de Mzo. de 2015
example
persistent a
if isempty (a)
a=0;
end
2 comentarios
Respuesta aceptada
Image Analyst
el 1 de Mzo. de 2015
You say "the value assigned to 'a' in the previous computation should be retained, after I close the m-file and run it next time." So, save it to a .mat file on disk with save() then. Recall it with load() the next time you run the program.
persistent a
if isempty (a)
a=0;
if exist('a.mat', 'file')
% Recall a from mat file
s = load('a.mat');
a = s.a;
end
end
% more code....
% Then just before you exit this routine, save it out to the disk file
% for recall by later runs of this program.
save('a.mat', a);
Of course since you're saving it and recalling it across different runs, it no longer needs to be persistent. You could just do load() and save() and not have it be persistent.
Más respuestas (1)
Walter Roberson
el 1 de Mzo. de 2015
That code looks fine in itself. See here for the examples in the documentation for persistent. persistent variables, like global variables, are initialized to [], so testing them for that value, just as you did, is correct for determining whether they have been initialized.
Note that persistent variables are only visible inside the routine they are declared in, so they are not the correct choice for creating a shared variable.
Ver también
Categorías
Más información sobre Get Started with MATLAB en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!