Sometimes we'd like to pause code execution to inspect the state of the application (see Debugging). When running code through the MATLAB editor, this can be done using the "Pause" button in the UI or by pressing Ctrl+c (on Windows). However, when a computation was initiated from a GUI (via the callback of some uicontrol
), this method does not work anymore, and the callback should be interrupted via another callback. Below is a demonstration of this principle:
function interruptibleUI
dbclear in interruptibleUI % reset breakpoints in this file
figure('Position',[400,500,329,160]);
uicontrol('Style', 'pushbutton',...
'String', 'Compute',...
'Position', [24 55 131 63],...
'Callback', @longComputation,...
'Interruptible','on'); % 'on' by default anyway
uicontrol('Style', 'pushbutton',...
'String', 'Pause #1',...
'Position', [180 87 131 63],...
'Callback', @interrupt1);
uicontrol('Style', 'pushbutton',...
'String', 'Pause #2',...
'Position', [180 12 131 63],...
'Callback', @interrupt2);
end
function longComputation(src,event)
superSecretVar = rand(1);
pause(15);
print('done!'); % we'll use this to determine if code kept running "in the background".
end
function interrupt1(src,event) % depending on where you want to stop
dbstop in interruptibleUI at 27 % will stop after print('done!');
dbstop in interruptibleUI at 32 % will stop after **this** line.
end
function interrupt2(src,event) % method 2
keyboard;
dbup; % this will need to be executed manually once the code stops on the previous line.
end
To make sure you understand this example do the following:
interruptibleUI.m
, such that the code starts on the very first line of the file (this is important for the 1st method to work).superSecretVar
.