3

I have a while loop, infinite, and I want to stop it when I press a keyboard key.

Pseudocode:

While(1)
    do stuff;

    listening for key;
    if key is pressed
        break;
    end
end

The function waitforbuttonpress makes me press the key, so no luck.

I've found no option on the web.

SamuelNLP
  • 4,038
  • 9
  • 59
  • 102

3 Answers3

3

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.

Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
3

GUI based solution I found in Matlab central

dialogBox = uicontrol('Style', 'PushButton', 'String', 'Break','Callback', 'delete(gcbf)');
while (ishandle(dialogBox))
    statements....
end
Shan
  • 511
  • 5
  • 13
1

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145