DankMasterDan
DankMasterDan

Reputation: 2123

Matlab onclick callback to execute function

I want Matlab to execute a function that takes the specific point I clicked on as an input, so for example, if I plot

plot(xy(:,1),xy(:,2))
scatter(xy(:,1),xy(:,2))

and then click on a specific point (see figure), it will execute a callback function whose inputs are not only the x,y coordinate of that point but also its index value (ie its the 4th row of variable xy)

Thanks alot!

enter image description here

Upvotes: 1

Views: 1021

Answers (1)

LowPolyCorgi
LowPolyCorgi

Reputation: 5171

This can be done by using the ButtonDownFcn property of Scatter objects.

In the main script:

% --- Define your data
N = 10;
x = rand(N,1);
y = rand(N,1);

% --- Plot and define the callback
h = scatter(x, y, 'bo');
set(h, 'ButtonDownFcn', @myfun);

and in the function myfun:

function myfun(h, e)

% --- Get coordinates
x = get(h, 'XData');
y = get(h, 'YData');

% --- Get index of the clicked point
[~, i] = min((e.IntersectionPoint(1)-x).^2 + (e.IntersectionPoint(2)-y).^2);

% --- Do something
hold on
switch e.Button
    case 1, col = 'r';
    case 2, col = 'g';
    case 3, col = 'b';
end
plot(x(i), y(i), '.', 'color', col);

i is the index of the clicked point, so x(i) and y(i) are the coordinates of the clicked point.

Amazingly enough, the mouse button which performed the action is stored in e.Button:

  • 1: left click
  • 2: middle click
  • 3: right click

so you can play around with that too. Here is the result:

enter image description here

Best,

Upvotes: 5

Related Questions