Monday, 23 May 2016

Matlab memory management

A couple of quick tips if you run out of memory in Matlab. All of these commands will have an almost insignificant impact on your actual work, but they might be useful in some occasions when Matlab gets cranky. It has happened to me before that Matlab runs out of "heap memory" when opening and closing figures. Then all you want to do is to save your work, exit and relaunch Matlab, but Matlab might complain that it doesn't have enough memory for that. So I'm listing a couple of commands that might just about allow you to save and exit without losing the content of your workspace.

  • pack This command calls Matlab's garbage collector. It only works from the command line, and if you call it inside a procedure it will return an error. You shouldn't need to use it, as Matlab calls its garbage collector automatically, but it might still be helpful if you're using some other software along with Matlab and you're running low on memory.
  • java.lang.Runtime.getRuntime.gc This command calls Java's garbage collector. Matlab's UI is largely written in Java, and when you open a lot of figures you sometimes incur in out of Java memory errors. This command has been helpful in some occasions as it's given me some leeway to save my work and restart Matlab.
  • java.lang.Runtime.getRuntime.freeMemory This command doesn't really free any memory, but it will show you the amount of memory available for the Java runtime environment. Using this you'll clearly see the effect of the previous gc command.