matlab - 在 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 中已经发生了鼠标点击?
解决方案
目前尚不清楚您是否希望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
功能。(您可以阅读在回调之间共享数据以了解有关其工作原理的详细信息。)
推荐阅读
- podman - 如何强制删除所有 podman 图像和子项
- java - System.out.println 在提供的 Stream 上不起作用?
- python - 如何在python中使用类似的switch case清除文本字段
- r - RStudio 查看器错误:未找到“会话/viewhtml ....”
- mysql - pdo 准备好的语句以无效的参数号退出
- azure - Azure 容器实例的静态 IP 地址
- impala - 在 Superset 上启用 Impala 模拟
- python - 在数据框列中选择并显示某个值
- javascript - 带有搜索和输入的 HTML 下拉框
- scala - 如何使用 Ignite 创建我自己的 CacheStore 以在二进制模式下存储值 (setStoreKeepBinary(true))