track the position of the mouse cursor

16 views (last 30 days)
rukhsar khan
rukhsar khan on 18 Mar 2017
Answered: Madheswaran on 9 Jan 2025
I want to track the position of the mouse cursor, for every seconds. Means when a mouse is moved - this tracker should start and plot the graph with respect to time( i.e; the x and y coordinate with respect to time). So how can i write this program in MATLAB.

Answers (1)

Madheswaran
Madheswaran on 9 Jan 2025
Hi Rukhsar
You can use 'get(groot, "PointerLocation") to get the current location of the cursor. Consider the following code for creating a live plot of cursor movements:
fig = figure('Name', 'Mouse Position Tracker');
x_positions = [];
y_positions = [];
timestamps = [];
start_time = tic; % Start timer
subplot(2,1,1);
h1 = plot(0,0,'b-'); % X-coordinate plot
title('X-Coordinate vs Time');
xlabel('Time (seconds)');
ylabel('X Position (pixels)');
grid on;
subplot(2,1,2);
h2 = plot(0,0,'r-'); % Y-coordinate plot
title('Y-Coordinate vs Time');
xlabel('Time (seconds)');
ylabel('Y Position (pixels)');
grid on;
while ishandle(fig) % Run until figure is closed
% Get current mouse position
currentPos = get(groot, 'PointerLocation');
current_time = toc(start_time);
x_positions = [x_positions currentPos(1)];
y_positions = [y_positions currentPos(2)];
timestamps = [timestamps current_time];
set(h1, 'XData', timestamps, 'YData', x_positions);
set(h2, 'XData', timestamps, 'YData', y_positions);
% Adjust axes limits automatically
subplot(2,1,1);
xlim([max(0, current_time-10) current_time+0.1]);
subplot(2,1,2);
xlim([max(0, current_time-10) current_time+0.1]);
% Pause for 1 second before next update
pause(1);
end
This code creates a window with two graphs that show your cursor's X and Y positions over time. The top graph (blue line) tracks horizontal movement, and the bottom graph (red line) tracks vertical movement. It updates every second and shows the last 10 seconds of movement. The tracking continues until you close the window.
Here is the output of the above code:
For more information, refer to the following documentations:
  1. groot - https://mathworks.com/help/matlab/ref/groot.html
  2. get - https://mathworks.com/help/matlab/ref/get.html
Hope this helps!

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!