getmousepos

Returns the mouse position in the figure area.

Syntax

[x, y] = getmousepos()

Outputs

x, y
The position of the mouse.
If the mouse is over a 2D plot, x and y are in the plot's coordinates system, which is defined by the x and y axes.
If the mouse is not over a 2D plot, then x and y are in the figure's coordinate system where the (0,0) point is in the upper-left corner of the figure window.

Examples

In the following example, getmousepos is used along with the 'mouseclickcallback' property to obtain the mouse position everytime you click on the plot:
close all;
plot(rand(100,1));
set(gca, 'mouseclickcallback',@get_mouse_pos);

function get_mouse_pos(handle, callbackdata)
  [x,y] = getmousepos() 
  callbackdata
end
The next example demonstrates the two coordinate systems. The mouse coordinates are printed in the console as the mouse moves over the figure.
close all;
figure();
subplot(1,2,2);
plot(rand(10,1));

ellipse(gcf,'pos',[0, 0, 20, 20], 'edgecolor', 'r','linewidth',2);

for i=1:100 
  [x,y] = getmousepos()
  pause(1);
end
getmousepos and the 'mouseclickcallback' property are combined in the following example to create new elements in the figure:
clear all, close all;
axes('position',[0,0,0,0]);
set(gca,'mouseclickcallback',@mouseclicked);

function mouseclicked(h,callbackdata)
  [x,y]=getmousepos();
  ellipse(gcf,'pos',[x-10, y-10, 20, 20]) 
end

Comments

If the mouse is not inside the figure area when getmousepos is called, the outputs will be NaN.