One way to easily read user inputs from the keyboard is to create a new figure and specify a KeyPressFcn callback function, which is executed automatically if any key is pressed.
Lets start off by creating a new figure. As we don't need the figure to display anything, let's make it as small as possible (i.e. 1 by 1 pixel) and place it at the lower corner of the display:
f = figure('Position',[0,0,1,1]);
Now we'll set the UserData property of the figure - which we will use as counter - to zero:
set(f,'UserData',0);
Now let's see what to do when a key is pressed: We can create a small callback function which checks if the pressed button was a space and increases the UserData counter if that was the case. We'll call that function isspace:
function isspace(hObject,callbackData)
if get(hObject,'CurrentCharacter') == ' '
set(hObject,'UserData',get(hObject,'UserData')+1);
end
end
Now simply set up the figure to use this function as KeyPressFcn by
set(f,'KeyPressFcn',@isspace);
This already counts the number of times space is pressed. The current value of the counter is read by
get(f,'UserData');
Now we need the time measurement. This can be done using a timer. We'll configure it to go off after 5 seconds and then assing a new value in the base workspace. For that we need a callback function timerCallback.m
function timerCallback(hObj,eventData)
assignin('base','nSpace',get(gcf,'UserData'));
delete(gcf);
stop(hObj);
delete(hObj);
end
t = timer('StartDelay',5,'TimerFcn',@timerCallback);
start(t);
And that's it: First create the figure, create the timer and after 5 seconds you get the number of key presses in the variable nSpace in your workspace and the window is closed.
One way to easily read user inputs from the keyboard is to create a new figure and specify a
KeyPressFcn
callback function, which is executed automatically if any key is pressed.Lets start off by creating a new figure. As we don't need the figure to display anything, let's make it as small as possible (i.e. 1 by 1 pixel) and place it at the lower corner of the display:
Now we'll set the
UserData
property of the figure - which we will use as counter - to zero:Now let's see what to do when a key is pressed: We can create a small callback function which checks if the pressed button was a space and increases the
UserData
counter if that was the case. We'll call that functionisspace
:Now simply set up the figure to use this function as
KeyPressFcn
byThis already counts the number of times space is pressed. The current value of the counter is read by
Now we need the time measurement. This can be done using a
timer
. We'll configure it to go off after 5 seconds and then assing a new value in the base workspace. For that we need a callback functiontimerCallback.m
And that's it: First create the figure, create the timer and after 5 seconds you get the number of key presses in the variable
nSpace
in your workspace and the window is closed.