[英]Getting clicked point coordinates in 3D figure 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
object 的datacursormode
。
將 function 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)
所有這些代碼實際上是數據游標使用的默認 function 的副本。 唯一的修改是:
最后一行代碼使用assignin
將 cursor 的 position 傳輸到base
工作區中的變量(名為clicked_point
)。
有了它,保留生成球體的代碼(盡管我建議您將表面 object 的名稱更改為sphere
以外的其他名稱,因為這是內置的 MATLAB 函數),我們只需要修改datacursormode
object 來指示它使用我們的getClickedPoint
function:
[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
function。(您可以閱讀Share Data Among Callbacks以詳細了解其工作原理。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.