In Matlab, is it possible to terminate a script, but save all its internal variables to workspace?

纵饮孤独 提交于 2019-11-27 07:52:05

MATLAB versions 2016a and later

If you are using post 2016a versions of Matlab there is actually a pause button that appears when you run the script (as described by @pedre). This allows you to pause the script, inspect variables and then resume afterwards.

Make sure to check out the next section as this may still be convenient.

Older MATLAB versions

Actually the trick is to use dbstop if error.

First use this, then run your script. Once you introduce an error (for example, with Ctrl+C), you then have the chance to inspect/save your workspaces manually.

You will not be able to resume the script.

Pedro Luque

You just have to click inside your script so you can get the Editor page open, and then press pause, and see all intern values there.

A colleague showed me an alternate way to incorporate this in my function, by attaching a save() command to the cancellation of a waitbar like so:

%appoint emergency file location
emergencysave = char(inputdlg({'fill in here:'}, 'windowtitle', 1, 'c:\defaultstringhere.mat'));

%or just emergencysave = 'c:\emergencysave.mat';



%create some GUI element you can cancel
times = 10;
wbinfo = struct('curlength', {0.0});
wb = waitbar(wbinfo.curlength);
wbinfo.wb = wb;



%attach save() to cancelling
anyimportantvariable = [];
for i=1:times
    anyimportantvariable = [anyimportantvariable, i^2];
    wbinfo.curlength = i/times;
    try
        waitbar(wbinfo.curlength, wb)
    catch
        save(emergencysave, 'anyimportantvariable');
        return;
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!