MATLAB Answers

Safely interrupt a script/function

3 ビュー (過去 30 日間)
Daniel
Daniel 2021 年 6 月 14 日
回答済み: Daniel 2021 年 6 月 15 日
I have a script which loops through an array and performs an action for each itetation which takes several seconds. Also, at the beginning of the script, a driver is loaded which has to be properly unloaded in order to not crash the hardware. Problem is that if you accidentally create a large array, you are stuck with two options: Either you Ctrl+C and go do the old unplug-replug, or you wait for 40h. Both are not feasable. Is there a way, then, to call a function upon the user terminating the program?
  1 件のコメント
Walter Roberson
Walter Roberson 2021 年 6 月 14 日
onCleanup()

サインインしてコメントする。

採用された回答

Daniel
Daniel 2021 年 6 月 15 日
As Walter suggested, onCleanup seems to be the most elegant solution

その他の回答 (1 件)

Jan
Jan 2021 年 6 月 14 日
You can open a small window, which contains a stop button. Pressing this button sets a local variable, which can be checked from your code. Catch errors with an error handling:
% [UNTESTED CODE]
function yourCode
FigH = figure('UserData', 0);
ButtonH = uicotrol('Style', 'PushButton', 'String', 'Stop', ...
'Callback', @StopCallback;)
try
resource = reserveYourResource();
for k = 1:1e6
drawnow;
if ~ishandle(FigH) || FigH.UserData
% Figure closed or stop button pressed:
disp('Stopped by user');
break
end
% Some dummy code:
pause(2)
disp(clock)
end
catch ME
disp('Stopped by error')
end
releaseResource(resuource);
end
function StopCallback(ButtonH, EventH)
FigH = ancestor(ButtonH, 'figure');
FigH.UserData = 1;
end

製品


リリース

R2020b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by