MATLAB Language Making a button in your UI that pauses callback execution


Example

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:

  1. Paste the above code into a new file called and save it as interruptibleUI.m, such that the code starts on the very first line of the file (this is important for the 1st method to work).
  2. Run the script.
  3. Click Compute and shortly afterwards click either Pause #1 or on Pause #2.
  4. Make sure you can find the value of superSecretVar.