Matlab onclick回调执行函数
Matlab onclick callback to execute function
我希望 Matlab 执行一个函数,将我点击的特定点作为输入,例如,如果我绘制
plot(xy(:,1),xy(:,2))
scatter(xy(:,1),xy(:,2))
然后点击一个特定的点(如图),会执行一个回调函数,回调函数的输入不仅是该点的x,y坐标,还有它的索引值(即变量xy的第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:右击
所以你也可以尝试一下。这是结果:
最佳,
我希望 Matlab 执行一个函数,将我点击的特定点作为输入,例如,如果我绘制
plot(xy(:,1),xy(:,2))
scatter(xy(:,1),xy(:,2))
然后点击一个特定的点(如图),会执行一个回调函数,回调函数的输入不仅是该点的x,y坐标,还有它的索引值(即变量xy的第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:右击
所以你也可以尝试一下。这是结果:
最佳,