title: Animate a MATLAB figure by pressing left and right arrow keys
body: <p>I am trying to change the radius of a sphere by using left and right arrow keys, plotted in a MATLAB figure. For example by pressing right arrow, the value of radius increases by one and then plot the new sphere with the updated radius. Similarly, pressing left arrow key decreases the radius by one and then plots a smaller sphere. However, I want this change to be limited between 1 and <code>rmax</code>.</p>
  
  <p>I got some ideas of how I can approach after reading <a href="https://stackoverflow.com/a/19579258/1227860">this post</a> but still it is not what I am looking for. Therefore, I used two global variables to achieve this task in order to somehow pass the information by reference to <code>KeyPressFcn</code> so when a key is pressed <code>KeyPressFcn</code> know what those limits are. In the example below, the code does increase and decrease the radius by one but it is it does not restrict the change of radius within the specified range after left and right arrows are hit.</p>
  
  <p>Is there a better way of approaching this? How can I pass the value of radius and its limits to <code>KeyPressFcn</code>? I want <code>KeyPressFcn</code> to know how much it can change the radius when left and right arrows are pressed.</p>
  
  <pre><code>function animateme()
  
  fig_h = figure;
  set(fig_h,'KeyPressFcn', @key_pressed_fcn);
  
  global r rmax
  
  p0 = [0 0 0];
  [x,y,z] = sphere; 
  
  rmax = 10;
  r = 1;
  
  while 1==1
  
      h = surf(x*r+p0(1), y*r+p0(2), z*r+p0(3)); 
      set(h, 'FaceAlpha', 0.5, 'FaceColor', rand([1 3]))
      axis equal;
  
      pause
  
  end
  
  
  
  function key_pressed_fcn(fig_obj, eventDat)
  
  global r rmax
  
  if strcmpi(eventDat.Key, 'rightarrow')
      r = r + 1;
      if r &lt; 1
          r = 1;
      end
  elseif strcmpi(eventDat.Key, 'leftarrow')
      r = r - 1;
      if r &gt; rmax
          r = rmax;
      end
  end
  disp(r)
  </code></pre>