MATLAB: How to obtain the coordinates of the mouse on the screen displayed somewhere in the figure window

axesaxiscoordinatecoordinatesfigureimageMATLABmousetrack;

I would like to obtain the coordinates of the mouse on the screen displayed somewhere in my figure window.

Best Answer

This enhancement has been incorporated in MATLAB 7.5 (R2007b).
As a workaround in previous MATLAB releases, you can use the following MATLAB function to track mouse motion:
function mousetrk
%MOUSETRK function to track mouse motion
% This function creates two static text controls
% which contain the x & y coordinates of the mouse
% The driving callback is executed by the
% WindowButtonMotionFcn of the figure.
figure
axes('Visible','off')
xbox = uicontrol('Style','text','Tag','xbox');
xboxlabel = uicontrol('Style','text','String','X Value',...
'Position',get(xbox,'position')+[0 21 0 0]);
ybox = uicontrol('Style','text','Position',[90 20 60 20],'Tag','ybox');
yboxlabel = uicontrol('Style','text','String','Y Value',...
'Position',get(ybox,'position')+[0 21 0 0]);
callback = ['pt = get(gca,''CurrentPoint'');'...
'xbox = findobj(''Tag'',''xbox'');' ...
'ybox = findobj(''Tag'',''ybox'');' ...
'set(xbox,''String'',num2str(pt(1,1)));' ...
'set(ybox,''String'',num2str(pt(1,2)));'];
set(gcf,'WindowButtonMotionFcn',callback);
For more information on the WindowButton functions, please refer to the Handle Graphics Property Browser: