mlock - Prevent clearing function or script from memory - MATLAB (original) (raw)

Main Content

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

Lock Function with Persistent Variable

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.

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

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.

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.

Unlock myFun so it can be cleared from memory.

Tips

Extended Capabilities

Thread-Based Environment

Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool.

This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.

Version History

Introduced before R2006a