Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MATLAB: Pause program and await keypress

I am writing a program in which at some point a graph is plotted and displayed on screen. The user then needs to press 'y' or 'n' to accept or reject the graph. My current solution uses the PsychToolbox (the actual solution doesn't need to), which includes a command called 'KbCheck' which checks at the time of calling the state of all the keyboard buttons. My code looks like this:

function [keyPressed] = waitForYesNoKeypress
keyPressed = 0; % set this to zero until we receive a sensible keypress
while keyPressed == 0 % hang the system until a response is given
    [ keyIsDown, seconds, keyCode ] = KbCheck; % check for keypress
    if find(keyCode) == 89 | find(keyCode) == 78 % 89 = 'y', 78 = 'n'
        keyPressed = find(keyCode);
    end
end

The problem is, that the system really does 'hang' until a key is pressed. Ideally, I would be able to scroll, zoom, and generally interact with the graphs that are plotted onscreen so that I can really decide whether or not I want to press 'y' or 'n'!

I have tried adding 'drawnow;' into the while loop above but that doesn't work: I still am unable to interact with the plotted graphs until after I've accepted or rejected them.

The solution doesn't have to use PsychToolbox; I assume there are plenty of other options out there?

Thanks

like image 771
CaptainProg Avatar asked Feb 16 '12 11:02

CaptainProg


People also ask

How do I pause MATLAB until keystroke?

disp('Press a key !' ) % Press a key here. You can see the message 'Paused: Press any key' in % the lower left corner of MATLAB window.

How do you pause a program in MATLAB?

Typing pause(inf) puts you into an infinite loop. To return to the MATLAB prompt, type Ctrl+C. Example: pause(3) pauses for 3 seconds. Example: pause(5/1000) pauses for 5 milliseconds.

What is the use of \t in MATLAB?

Accepted Answer The ability to use the "\t" format in a listbox in MATLAB to place a tab in a string expression is not available. As a workaround, you can use spaces along with a fixed-width font to align the columns. str(k) = {sprintf('%2i %5.2f %3i', k, ...

Which command is used to pause a program in MATLAB?

pause (MATLAB Functions) pause, by itself, causes M-files to stop and wait for you to press any key before continuing. pause(n) pauses execution for n seconds before continuing, where n can be any real number.


2 Answers

I'd use the input function:

a = input('Accept this graph (y/n)? ','s')

if strcmpi(a,'y')
    ...
else
    ...
end

Although admittedly it requires two keypresses (y then Enter) rather the one.

like image 145
Chris Taylor Avatar answered Oct 05 '22 16:10

Chris Taylor


Wait for buttonpress opens up a figure, which may be unwanted. Use instead

pause('on');
pause;

which lets the user pause until a key is pressed.

like image 44
patrik Avatar answered Oct 05 '22 14:10

patrik