2015-04-01 87 views
1

我想Matlab来执行一个函数,具体点我点击作为输入,因此,例如,如果我绘制Matlab的的onclick回调执行功能

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

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

非常感谢!

enter image description here

回答

4

这可以通过使用Scatter对象的ButtonDownFcn属性来完成。

在主脚本:

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

最佳,