How do I obtain the coordinates of the mouse on the screen displayed somewhere in my figure window?

Illustration
rew_sahsani - 2024-01-30T15:59:50+00:00
Question: How do I obtain the coordinates of the mouse on the screen displayed somewhere in my figure window?

How do I obtain the coordinates of the mouse on the screen displayed somewhere in my figure window?

Expert Answer

Profile picture of Prashant Kumar Prashant Kumar answered . 2025-11-20

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);

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!