Reputation: 147
I have a function that displays a graph with some random elements. I want to have it so that when the user presses a certain key the function runs again, redistributing these random elements on the graph. What is the best way to go about doing this?
Upvotes: 1
Views: 192
Reputation: 4650
You want to set a key press callback for a figure you're using in a script by using the KeyPressFcn
like so:
h = figure('KeyPressFcn',@testcallback);
Then place the following in a function testcallback.m
file (you can also use a function handle):
function testcallback(hObject,callbackdata)
% Check to make sure key pressed is the escape key
if (strcmp(callbackdata.Key,'escape'))
% Do whatever processing you want
imshow(rand(40));
end
end
When you run the script, a figure will appear. Everytime you press escape
, the function will fire:
Upvotes: 1
Reputation: 366
using the input()
function in MATLAB allows you to prompt and ask a user for input. You can use this function to prompt the user to enter a key, when this key is entered, your function can be called and re-run.
Documentation on this can be found on the Mathworks website
Upvotes: 0
Reputation: 104484
You can wrap this within a while
loop and using ginput
. Put your function call within a while
loop, use ginput
and poll for a keystroke, and while this key is being pushed, keep going. Something like this, assuming that your figure is open after each call to the function:
while true
%// Generate random data
%// Call function
%// Open figure
%// Get a key from the user
[~,~,b] = ginput(1);
%// If you push C or c, then continue
if b == 67 || b == 99
continue;
else %// Else, get out
break;
end
end
Upvotes: 2