Documentation

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

mlock

Prevent clearing function or script from memory

Syntax

mlock

Description

example

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.

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.

Introduced before R2006a

Was this topic helpful?