matlab学习之persistent变量的使用

今天看到一个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;


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值