MATLAB: How to display the mouse position while moving strictly within an Axes

MATLAB

I want to display the mouse position when it moves over an Axes; however, I do not want it to display while I hover over the Figure. 
Currently, I use 'WindowButtonMotionFcn' to define a callback, '@MouseDisplay', that is triggered when the mouse moves over the Figure window. This callback gets the current mouse position within the Axes, and displays it. I partially solved this issue on my own by finding the pixel coordinate of the axis and using that to selectively display when inside the bounds of the Axes only, as defined by 'Position' or 'OuterPosition'. The problem is that when I zoom in to the image, the display then shows the mouse position when hovering over the Figure outside of the Axes again.
How can I make this robust to zooming?

Best Answer

You can use the "xlim" and "ylim" properties of the Axes in order to determine the boundary between the Axes and the Figure. When you zoom in, the "xlim" and "ylim" properties adjust to define the maximum and minimum values of the X- and Y- values currently displayed in the Axes. Therefore, this is a more robust way to test whether or not the mouse is within the Axes boundary.
Sample Code for the "@MouseDisplay" callback, given a Figure "f" and an Axes "a":
function MouseDisplay(~,~)
% Get the current point of the mouse over the Axes,
  % defined as the actual(X,Y) value
currPtValue= get(a,'CurrentPoint');
  % Get the current point of the mouse over the Figure, defined in pixels
currPtPixels= get(f,'CurrentPoint');
  % Use the Axes "xlim" and "ylim" properties in order to determine the X- and Y-
  % ranges within the Axes (i.e. maximum and minimum values in each dimension)
xlim = get(a,'xlim');
ylim = get(a,'ylim');
  % Define the boundaries as the max and min X- and Y- values
  % displayed within the Axes
outOfBoundsX = (xlim(1) <= C(1,1) && xlim(2) >= C(1,1));
outOfBoundsY = (ylim(1) <= C(1,2) && ylim(2) >= C(1,2));
  % Only print the mouse position (relative to the figure in pixels)
  % if the mouse is within the boundaries of the Axes
if outOfBoundsX && outOfBoundsY
disp(currPtPixels) % Simply prints to Command Window
end
end