Main Content

mlock

Prevent clearing function or script from memory

Syntax

Description

example

mlocklocks the currently running function in memory. Locking a function preventsclearfrom removing it from memory, and prevents reinitialization of anypersistentvariables defined in the file.

Usemlockonly within a MATLAB®code file.

To remove a locked function or script from memory, first unlock it using themunlockcommand, and then use theclearcommand.

Examples

collapse all

Create the functionmyFunin your current working folder.

functionmyFun()persistentnifisempty(n) n = 0;endn = n+1end

At the command prompt, callmyFuntwice. Each time you call the function, the value ofnincreases because it ispersistent.

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.

clearmyFunmyFun myFun
n = 1 n = 2

Edit themyFunfunction to include a call tomlock.

functionmyFun() mlockpersistentnifisempty(n) n = 0;endn = n+1end

At the command prompt, callmyFun3 times.

myFun myFun myFun
n = 1 n = 2 n = 3

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

clearmyFunmyFun myFun
n = 4 n = 5

UnlockmyFunso it can be cleared from memory.

munlock('myFun')

Tips

  • To lock a MEX file, use themexLockfunction.

Introduced before R2006a