2015-04-01 85 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

最佳,