Main Content

mlock

Prevent clearing function or script from memory

Syntax

Description

mlock locks the currently running function in memory. Locking a function prevents clear from removing it from memory, and prevents reinitialization of any persistent variables defined in the file.

Use mlock only within a MATLAB® code file.

To remove a locked function or script from memory, first unlock it using the munlock command, and then use the clear command.

example

Examples

collapse all

Create the function myFun in your current working folder.

function myFun()
    persistent n
    if isempty(n)
        n = 0;
    end
    n = n+1
end

At the command prompt, call myFun twice. Each time you call the function, the value of n increases because it is persistent.

myFun
myFun
myFun
n =

     1


n =

     2


n =

     3

Clear the function and call it another two times. Clearing the function also clears the persistent variable.

clear myFun
myFun
myFun
n =

     1


n =

     2

Edit the myFun function to include a call to mlock.

function myFun()
    mlock
    persistent n
    if isempty(n)
        n = 0;
    end
    n = n+1
end

At the command prompt, call myFun 3 times.

myFun
myFun
myFun
n =

     1


n =

     2


n =

     3

Try to clear the function and call it another two times. Since myFun is locked, clearing the function does not remove it from memory and does not clear the persistent variable.

clear myFun
myFun
myFun
n =

     4


n =

     5

Unlock myFun so it can be cleared from memory.

munlock('myFun')

Tips

  • To lock a MEX file, use the mexLock function.

Extended Capabilities

Version History

Introduced before R2006a