Main Content


Consolidate workspace memory


pack filename


pack frees up needed space by reorganizing information so that it only uses the minimum memory required. All variables from your base and global workspaces that are less than 2GB are preserved. Any persistent variables that are defined at the time are set to their default value (the empty matrix, []).


The pack function is unable to preserve variables larger than 2GB. It clears them from your workspace.

Do not use the pack function with objects that define events and listeners. The pack function causes the destructor of any listeners defined for the objects in the workspace. For information on restoring listeners when saving objects, see Restore Listeners.

The MATLAB® software temporarily stores your workspace data in a file called tp######.mat (where ###### is a numeric value) that is located in your temporary folder. (You can use the command dir(tempdir) to see the files in this folder).

pack filename frees space in memory, temporarily storing workspace data in a file specified by filename. This file resides in your current working folder and, unless specified otherwise, has a .mat file extension.

pack('filename') is the function form of pack.


Change the current folder to one that is writable, run pack, and return to the previous folder.

cwd = pwd;


You can only run pack from the MATLAB command line.

If you specify a filename argument, that file must reside in a folder for which you have write permission.

The pack function does not affect the amount of memory allocated to the MATLAB process. You must quit MATLAB to free up this memory.

Since MATLAB uses a heap method of memory management, extended MATLAB sessions may cause memory to become fragmented. When memory is fragmented, there may be plenty of free space, but not enough contiguous memory to store a new large variable.

If you get the Out of memory message from MATLAB, the pack function may find you some free memory without forcing you to delete variables.

The pack function frees space by

  • Saving all variables in the base and global workspaces to a temporary file.

  • Clearing all variables and functions from memory.

  • Reloading the base and global workspace variables back from the temporary file and then deleting the file.

If you use pack and there is still not enough free memory to proceed, you must clear some variables. If you run out of memory often, you can allocate larger matrices earlier in the MATLAB session and use these system-specific tips.

  • When running MATLAB on The Open Group UNIX® platforms, ask your system manager to increase your swap space.

  • On Microsoft® Windows® platforms, increase virtual memory using the Windows Control Panel.

To maintain persistent variables when you run pack, use mlock in the function.

See Also


Introduced before R2006a