How to avoid MATLAB crash when opening too many figures?

后端 未结 3 1489
野趣味
野趣味 2020-12-16 14:28

Sometimes I start a MATLAB script and realize too late that it is going to output way too many figures. Eventually I get an

Exception in thread \"AWT

相关标签:
3条回答
  • 2020-12-16 14:53

    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.

    0 讨论(0)
  • 2020-12-16 15:02

    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.

    0 讨论(0)
  • 2020-12-16 15:09

    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.

    0 讨论(0)
提交回复
热议问题