Stop a infinite while loop pressing a key in Matlab

时光毁灭记忆、已成空白 提交于 2019-12-06 01:08:00

I suppose if you don't want to resort to multithreading (one thread doing the computation in the while loop, another one waiting for input and setting a global sentinel value to break the while loop) you can try to implement breaking the loop on catching a keyboard-interrupt (ctrl-c). This should be possible, albeit in a kinda hackish way.

OK, I know this is a bit late but, I found a solution after a long hunt. When a figure window is focused, you can do this:

set(gcf,'currentchar',' ')         % set a dummy character
while get(gcf,'currentchar')==' '  % which gets changed when key is pressed
   do_stuff()
end

When a key is pressed while focus is in a figure, it sets the property 'currentchar'. Tested in R2010b.

GUI based solution I found in Matlab central

dialogBox = uicontrol('Style', 'PushButton', 'String', 'Break','Callback', 'delete(gcbf)');
while (ishandle(dialogBox))
    statements....
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!