首页 > 解决方案 > 在 3D 图 Matlab 中获取点击的点坐标

问题描述

我在 Matlab 中有一个 3D 图形,假设它是球体。我需要的是获取我用鼠标单击的表面点的X, Y,值。Z

r = 10;
[X,Y,Z] = sphere(50); 
X2 = X * r;
Y2 = Y * r;
Z2 = Z * r;
figure();
props.FaceColor = 'texture';
props.EdgeColor = 'none';
props.FaceLighting = 'phong';
sphere = surf(X2,Y2,Z2,props);
axis equal
hold on

clicked_point = [?,?,?];

在此处输入图像描述

所以在这个例子中,我希望clicked_point等于[-3.445,-7.32,5.878]

我试过这样的解决方案:

clear all;
close all;
r = 10;
[X,Y,Z] = sphere(50);
X2 = X * r;
Y2 = Y * r;
Z2 = Z * r;
fig = figure();
props.FaceColor = 'texture';
props.EdgeColor = 'none';
props.FaceLighting = 'phong';
sphere = surf(X2,Y2,Z2,props);
axis equal

dcm_obj = datacursormode(fig);
set(dcm_obj,'DisplayStyle','datatip',...
'SnapToDataVertex','off','Enable','on')
c_info = getCursorInfo(dcm_obj);

while length(c_info) < 1
    datacursormode on
    c_info = getCursorInfo(dcm_obj);
end

但在那之后我什至不能点击球体来显示任何数据。我怎样才能在脚本中获得X, Y, ?Z如果没有,我怎样才能检测到在 Matlab 中已经发生了鼠标点击?

标签: matlabgeometrymatlab-figurefiguresurface

解决方案


目前尚不清楚您是否希望clicked_point变量驻留在基础工作区中,或者它是否将成为 GUI 的一部分。

我将为您提供基本工作区的解决方案。

诀窍是只需将您需要的代码添加到UpdateFcn对象datacursormode中。

将函数保存getClickedPoint.m在 MATLAB 路径上可见的位置:

function output_txt = getClickedPoint(obj,event_obj)
% Display the position of the data cursor
% obj          Currently not used (empty)
% event_obj    Handle to event object
% output_txt   Data cursor text string (string or cell array of strings).

pos = get(event_obj,'Position');
output_txt = {['X: ',num2str(pos(1),4)],...
    ['Y: ',num2str(pos(2),4)]};

% If there is a Z-coordinate in the position, display it as well
if length(pos) > 2
    output_txt{end+1} = ['Z: ',num2str(pos(3),4)];
end

assignin('base','clicked_point',pos)

所有这些代码实际上是数据游标使用的默认函数的副本。唯一的修改是:

  • 我更改了名称(显然您希望它是唯一的)
  • 我添加了最后一行代码

最后一行代码用于assignin将光标的位置转移到工作区中的变量(名为clicked_point)中base

有了这个,保留生成球体的代码(尽管我建议您将表面对象的名称更改为其他名称,而不是sphere因为这是内置的 MATLAB 函数),我们只需要修改datacursormode对象以指示它使用我们的getClickedPoint功能:

[X,Y,Z] = sphere(50);
r = 10 ; X2 = X * r; Y2 = Y * r; Z2 = Z * r;
fig = figure ;
hs  = surf(X2,Y2,Z2,'FaceColor','texture','EdgeColor','none','FaceLighting','phong');
axis equal

%% Assign custom update function to dcm
dcm_obj = datacursormode(fig);
set(dcm_obj,'SnapToDataVertex','off','Enable','on','UpdateFcn',@getClickedPoint)

现在第一次单击球体时,clicked_point将在工作区中使用该点的坐标创建变量。每次您再次单击球体时,变量都会更新:

在此处输入图像描述


如果这要与 GUI 一起应用,请使用相同的技术,但不要使用assignin,我建议使用该setappdata功能。(您可以阅读在回调之间共享数据以了解有关其工作原理的详细信息。)


推荐阅读