How to avoid MATLAB crash when opening too many figures?

痴心易碎 提交于 2019-11-29 03:30:34
Jonas

In general, I'd suggest setting maximum Java Heap Memory to about 25% of the available RAM, which allows you to open lots of figures (but not infinite numbers). If you cannot do this in the preferences (e.g. b/c you have a Mac like mine), this solution will help - it overrides the preference settings.

The linked solution also tells you how much free java memory you have left, and how much total is available: Run the following commands:

java.lang.Runtime.getRuntime.maxMemory
java.lang.Runtime.getRuntime.totalMemory
java.lang.Runtime.getRuntime.freeMemory 

Unfortunately, a figure doesn't take a fixed amount of Java memory, an empty figure takes much less than one displaying 10k points, and a minimized figure takes less memory than a maximized one. However, if you can estimate the average memory needed per figure, you can indeed write a wrapper for figure that checks whether it's likely that this figure will be the last. Alternatively/additionally, you could make the wrapper function minimize all other figures (see Undocumented Matlab for this).

EDIT As pointed out by @Peter Lawrey, you may also try and perform garbage collection before checking how much memory is available - though I don't know whether Matlab would try that, anyway.

You can check the free memory, if there is no enough trigger a GC and check again. If there is still not enough, fail. You might want to allow 1-10 MB head room.

You can use Runtime.gc() and Runtime.freeMemory();

If you don't set the maximum memory it will make it a percentage of the available memory.

I use the findobj function in my own function 'limfig', where imglimit sets the amount of figures you want to be allowed to open at one time.

function y=limfig
imglimit=15;
if length(findobj('type','figure'))<imglimit
    y=figure; 

else
    'too many figures already open'
    return
end
end

Save this short code as limfig.m and then in any other code use the line f=limfig instead of f=figure.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!