Matlab onclick回调执行函数

时间:2015-04-01 20:18:00

标签: matlab user-interface callback

我希望Matlab执行一个函数,该函数将我点击的特定点作为输入,例如,如果我绘制

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

然后点击一个特定的点(见图),它将执行一个回调函数,其输入不仅是该点的x,y坐标,还有它的索引值(即它的第四行变量xy)< / p>

非常感谢!

enter image description here

1 个答案:

答案 0 :(得分:4)

可以使用ButtonDownFcn个对象的Scatter属性来完成此操作。

在主脚本中:

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

并在函数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是点击点的索引,因此x(i)y(i)是点击点的坐标。

令人惊讶的是,执行操作的鼠标按钮存储在e.Button

  • 1:左键单击
  • 2:中间点击
  • 3:右键单击

所以你也可以玩这个。结果如下:

enter image description here

最佳,

相关问题