MATLAB: How to use ‘CancelRequested’ property for a progress bar

app designerMATLAB

I currently have an App Designer program set up to run calculations in batches. While running the batch calculations, I'd like to have a way to stop the process without getting a bunch of errors (which is what happens when I close the app or progress bar window). Using the 'Cancel' button in the dialog box as a way to kick the program out of the loop appears to be the right choice, but the documentation for this feature is too sparse to be of any use. Has anyone gotten this feature to work and willing to share how to code it?
Thanks in advance.

Best Answer

fig = uifigure;
dlg = uiprogressdlg(fig,'Title','Wait',...
'Message','Starting','Cancelable','on','CancelText','Stop this');
wholeRandNum = 37;
for ii = 1:wholeRandNum
%you can put all your other code here
if isempty(findobj(fig)) == 1
dlg.CancelRequested = 1;
end
if dlg.CancelRequested == 1
disp('You Hit Cancel or Exited')
delete(fig)
return
end
dlg.Value = ii/wholeRandNum;
dlg.Message = sprintf('%12.2f%% complete',ii/wholeRandNum*100);
pause(0.1)
end