1

I am writing a matlab script that will perform calculations in a for loop, but would like it to break out of the for loop when 'return' is entered. I found a function that will listen for keystrokes and modified it to know when 'return' is pressed, but I can't figure out how to make it control what is going on in the main script.

Pseudo Code:

h_fig = figure;
set(h_fig,'KeyPressFcn',@myfun)

for ii = 1:50
        break when enter is pressed
end


    function y = myfun(src,event)
        y = strcmp(event.Key,'return');
        %disp(event.Key);
        if y == 1
            fprintf('Enter key pressed')
            return
        end
    end
lusius188
  • 11
  • 2

1 Answers1

0

It seems like you are creating the window only so you can capture the return key press. If this is the case, there is a better alternative: kbhit (in Octave a similar function with the same name comes built-in). Simply copy the kbhit.m file from that File Exchange submission to your current folder (or any directory that you can add to your MATLAB path using addpath), and do as follows:

kbhit('init');
for ii = 1:50
   if kbhit == 13
      break
   end
   % computations here...
end

If you want to use a window anyway, the right way to do so is to poll the "CurrentCharacter" property of the figure window:

h_fig = figure;
set(h_fig,'CurrentCharacter','') % use this if the figure has been around for longer, to reset the last key pressed
for ii = 1:50
   drawnow % sometimes events are not handled unless you add this
   if double(get(h_fig,'CurrentCharacter'))==13
      break
   end
   % computations here...
end

I could not get the above code to work in Octave, it seems that it doesn't update figure properties even with drawnow, not sure why. But I'm fairly sure the above works with MATLAB.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120