Search code examples
matlabuser-inputkeyboard-events

Detect Keyboard Input Matlab


I have a simple question, although it's harder than it seems; I couldn't find the answer on the interwebs :O

I'm writing a script in Matlab. What I want to do is the following:

  • When I press the esc key, I want a helpdialogue to pop up, so my script pauses. (So when I press esc, I want to stop the whole script to run so that the car (which im writing the script for) stops driving)

How do I do this? How can I say to Matlab: When I press esc, do this...

Thanks for your time guys!

EDIT: It's no option to implement something which awaits the keypress. Im writing a script for a driving car. It just has to drive around basically, but when I press esc for example, it should stop driving. So the script just has to run, untill I press the esc key; then the script has to pause.


Solution

  • In a matlab figure you can define a 'KeyPressFcn' that works similar to do what you ask.

    If you are in the console you have to work around that matlab is single threaded. Basically you need to halt the program flow to check for key presses.

    btw - also when you use 'KeyPressFcn' you will need to make some pauses so that Matlab will check if anything has happened.

    btw2 - I should also add during this pauses Matlab will not only read your key presses - but also do some housekeeping such as redrawing its window and stuff.