マウスで選択した位置​付近のデータ値を取得​するにはどうすればよ​いですか?

19 views (last 30 days)
MathWorks Support Team
MathWorks Support Team on 15 Oct 2009
PLOT関数でラインを表示しています。座標軸上をマウスで選択し、マウスに最も近いデータ点の値とそのインデックスを取得する方法を教えてください。

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jan 2020
Edited: MathWorks Support Team on 27 Jan 2020
Axes の "CurrentPoint"プロパティで、マウスが選択された位置を検出し、プロットされたデータと最も近いインデックスを計算します。
以下に例を示します。
% グラフ表示
X = linspace(-2*pi,2*pi,20);
Y = 5*sin(X)./X;
plot(X,Y,'x-')
axis equal
% ここで、ライン上をマウスで選択します。
% この例では、WAITFORBUTTONPRESSコマンドを使い
% 入力待ち状態にします。
waitforbuttonpress;
% マウスの現在値の取得
Cp = get(gca,'CurrentPoint');
Xp = Cp(2,1); % X座標
Yp = Cp(2,2); % Y座標
% マウスで選択した位置と最も近いデータのインデックスを計算
[dp,Ip] = min((X-Xp).^2+(Y-Yp).^2);
% マウスで選択した位置と最も近いデータ値を取得
Xc = X(Ip);
Yc = Y(Ip);
% テキストの挿入
str1 = sprintf('\\leftarrow クリックした場所');
str2 = sprintf(['最も近いデータ点: (%f,%f) \\rightarrow'],Xc,Yc);
ht(1) = text(Xp,Yp,str1,'Clipping','off');
ht(2) = text(Xc,Yc,str2,'Clipping','off', 'HorizontalAlignment','right');
set(ht,'FontSize',8,'Color','red')
また、以下の例は、UICONTEXTMENU関数を使用し、マウスで選択された位置を表示する例です。表示されたライン上を右クリックすると、選択した座標値が表示されます。
x=0:.01:2*pi;
y=sin(x);
h=plot(x,y);
hc=uicontextmenu;
hm=uimenu('parent',hc);
set(h,'uicontextmenu',hc);
set(gcf,'windowbuttondownfcn', ...
'pt=get(gca,''currentpoint'');set(hm,''label'',[num2str(pt(1,1)) '', '' num2str(pt(1,2))])')

More Answers (0)

Categories

Find more on 時系列オブジェクト in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!