Stop and continue execution from debugger possible?

Solution 1:

This is not necessarily the best way, but you could simulate a file-based signal/interrupt framework. It could be done by checking every once in a while inside the long simulation loop for the existence of a specific file. If it does, you enter interactive mode using the keyboard command.

Something along the lines:

CHECK_EVERY = 10;    %# like a polling rate

tic
i = 1;               %# loop counter
while true           %# long running loop
    if rem(i,CHECK_EVERY) == 0 && exist('debug.txt','file')
        fprintf('%f seconds since last time.\n', toc)
        keyboard
        tic
    end

    %# ... long calculations ...    

    i = i + 1;
end

You would run your simulation as usual. When you would like to step in the code, simply create a file debug.txt (manually that is), and the execution will halt and you get the prompt:

2.803095 seconds since last time.
K>> 

You could then inspect your variables as usual... To continue, simply run return (dont forget to temporarily rename or remove the file). In order to exit, use dbquit


EDIT: Just occurred to me, instead of checking for files, an easier solution would be to use a dummy figure as the flag (as long as the figure is open, keep running).

hFig = figure; drawnow
while true
    if ~ishandle(hFig)
        keyboard
        hFig = figure; drawnow
    end

    %# ...
    pause(0.5)
end

Solution 2:

With the release of R2016a, you can just hit the Pause button in the code editor and it will halt right away. The keyboard shortcut is Ctrl+F5.

To pause the execution of a program while it is running, in the Editor tab, click the Pause button. MATLAB pauses execution at the next executable line*.

When your code is running, the Start button will turn into a pause:

enter image description here

Another change with this release is the ability to add/remove breakpoints while running. Previously you couldn't do this, apparently.