tqjustc
tqjustc

Reputation: 3814

how can I get the current mouse position using a click. MATLAB

In this post,Matlab: How to get the current mouse position on a click by using callbacks , it shows something as follows:

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

However, I cannot get the pos and use it in mytestfunction(). could anyone help ? Thanks !

Upvotes: 1

Views: 1130

Answers (1)

chappjc
chappjc

Reputation: 30579

If you are not using GUIDE and hence do not have the handles structure (see bottom), you can utilize the UserData property of the figure to pass any information:

set(gcf,'UserData',pos);

Then you can access pos from anywhere else via:

pos = get(gcf,'UserData');

See this MathWorks description of the UserData property, and this full example. From the first page:

All GUI components, including menus and the figure itself have a UserData property. You can assign any valid MATLAB workspace value as the UserData property's value, but only one value can exist at a time.

As a workaround to this limitation, you could assign a struct to UserData that has all the properties needed by your program stored in different fields.

A detail I left out in the commands above is the figure/object handle (you probably don't actually want to use gcf). In mytestfunction you have it stored in f. In the callback you can find the parent figure of the hObject by:

f = ancestor(hObject,'figure');

One way to use the above approach is to simply wait for changes in the UserData property:

function mytestfunction()
f=figure; set(f,'WindowButtonDownFcn',@mytestcallback)
maxPos=10; cnt=0;
while cnt<maxPos, waitfor(f,'UserData'); pos=get(gcf,'UserData'), cnt=cnt+1; end

function mytestcallback(hObject,~)
pos=get(hObject,'CurrentPoint');
set(ancestor(hObject,'figure'),'UserData',pos);

Note that another way to handle events is to implement a listener to respond to the clicking event, but the WindowButtonDownFcn callback should work fine.


Originally, I was thinking GUIDE, in which you would have the handles structure. This is one purpose of the handles structure. Store the position in a field of handles, and update it:

 handles.pos = pos;          % store it
 guidata(hObject,handles);   % update handles in GUI

Then back in mytestfunction or whatever other callback needs access to pos, you can use handles.pos, if the handles structure is up to date.

Upvotes: 4

Related Questions