今天看到一个MATLAB程序,看到一个声明为persistent的变量,不知persistent为何意思,help persistent。
persistent Define persistent variable.
persistent X Y Z defines X, Y, and Z as variables that are local
to the function in which they are declared yet their values are
retained in memory between calls to the function. Persistent
variables are similar to global variables because MATLAB creates
permanent storage for both. They differ from global variables in
that persistent variables are known only to the function in which
they are declared. This prevents persistent variables from being
changed by other functions or from the MATLAB command line.
Persistent variables are cleared when the M-file is cleared from
memory or when the M-file is changed. To keep an M-file in memory
until MATLAB quits, use MLOCK.
If the persistent variable does not exist the first time you issue
the persistent statement, it will be initialized to the empty matrix.
It is an error to declare a variable persistent if a variable with
the same name exists in the current workspace.
persistent的作用如下:
1.把在函数中声明的局部变量保存到内存中,供以后调用该函数使用。定义的变量类似全局变量会一直存在内存中,但不同的是persistent变量只能被所被定义的函数使用,这样能够防止被其他函数或其他命令所改变。
2.persistent变量只有在m文件被改变或被从内存中清除,该变量才会被清除。
3.persistent变量初始化为一个空矩阵。
function out=load_data();
% We load the data the first time we run the program.
persistent loaded;
persistent w;
if(isempty(loaded)) %判断之前是不是已调用过了
v=zeros(10304,400);
for i=1:40
cd(strcat('s',num2str(i))); %进入一个文件夹
for j=1:10
a=imread(strcat(num2str(j),'.bmp')); %读入该文件夹下的bmp
v(:,(i-1)*10+j)=reshape(a,size(a,1)*size(a,2),1); %保存为矩阵的一列数据
end
cd ..
end
w=uint8(v); % Convert to unsigned 8 bit numbers to save memory.
end
loaded=1; % Set 'loaded' to aviod loading the database again.
out=w;