Matlab: How to get the current mouse position on a click by using callbacks

Define the WindowButtonDownFcn of your figure callback using the set command and an @callbackfunction tag.

Like so:

function mytestfunction()
f=figure;
set(f,'WindowButtonDownFcn',@mytestcallback)

function mytestcallback(hObject,~)
pos=get(hObject,'CurrentPoint');
disp(['You clicked X:',num2str(pos(1)),', Y:',num2str(pos(2))]);

You can also pass extra variables to callback functions using cell notation:

set(f,'WindowsButtonDownFcn',{@mytestcallback,mydata})

If you’re working with uicontrol objects, then it’s:

set(myuicontrolhandle,'Callback',@mytestcallback)

Leave a Comment