You may want, at some point, to interrupt your code with a keypress (e.g. to trial returning from an arbritary point). These are instructions for (one way) of getting a keypress in matlab.

I'm assuming you have a function which contains some kind of 'main loop'. If not, you may need to adjust the following. Note it also needs to be a function not a script, so you can embed another function within it!

1. Add the following to the top of your code somewhere:

% Setup input window and flag
figure('Position',[50,800,250,250],'MenuBar','none','Name','Food found input','NumberTitle','off');
set(gcf,'WindowButtonDownFcn',@setFoodFlag); % Mouse click
set(gcf,'KeyPressFcn',@setFlag); % Key press
foodFlag = 0;


2. Within your main loop, add the following code:

% Check for click on food window
if foodFlag == 1
disp('Food found!');
% ... do stuff
foodFlag = 0; % Reset flag
end
drawnow; % Need this to register button presses

You should add code (or call a function, change state, etc.) to deal with finding food where it says '... do stuff'


3. Finally, add this nested function within your function somewhere (e.g. at the bottom of all your code)

% This function gets called on click / button press
function setFoodFlag(~,~)
foodFlag = 1;
end


The effect of all this is that a little window will appear, and clicking on this or pressing any key (while the window has focus) will cause the foodFound flag to get set.

If you'd rather just have mouse click / key press, remove the appropriate 'set' command. You could also do something fancier in the setFoodFlag function to just get a single key (e.g. enter), by checking the event properties or something. If anyone is fussed about this, ask me!


Overall, your function might look like this: