Tuesday 21 April 2015

Matlab - exit infinite while loop with a keypress

This code is for an infinite while loop in Matlab, it will check to see if the 'q' key has been pressed, it when then ask do you really want to quit (Yes/No) and then exit the while loop.

 
close
clear all
clc
figure('doublebuffer','on', ...
'CurrentCharacter','a', ...
'WindowStyle','modal')

t=text(.5,.5,datestr(now),'Hor','center');

while (1)

% your code here
set(t,'String',datestr(now));
% your code ends

pause(.01); % added to pause and allow screen/ keyboard buffer to update

if double(get(gcf,'CurrentCharacter')) == 113 % check if 'q' key pressed, change to 27 for escape
choice = menu('Quit code yes or no?','Yes','No');
if choice==1 | choice==0
break; % break from while loop
end
set(gcf,'currentch',char(1)) % Sets current char as 1 or it would just keep asking to quit
end

end

set(t,'String','While loop exited, finished');
set(gcf,'WindowStyle','normal');

 

No comments:

Post a Comment