Here are 2 methods to capture mouse coordinates within the axes of a figure.
In these demos the coordinates of the cursor's current point on the axes will appear in the text box. When the mouse leaves the axes, the textbox will clear.
Be aware of the limit in precision of CurrentPoint within axes (see this explanation). For example, you may not be able to select an exact coordinate such as (0,0). Method 1: Use a pointer manager (requires Image Processing Toolbox)
Instead of using the WindowButtonMotionFcn which requires you to detect when the mouse enters the axes, use a pointer manager assigned to the axes that returns the axes' current point when the mouse is over the axes. This is more efficient than the WindowButtonMotionFcn.
Add this to you app's startup function.
Key components
pm.exitFcn = @(~,~) set(app.CurrentPositionEditField, 'Value', '');
pm.traverseFcn = @(~,~) set(app.CurrentPositionEditField, 'Value',...
sprintf('%.2f, %.2f', app.UIAxes.CurrentPoint(1,1:2)));
iptSetPointerBehavior(app.UIAxes, pm)
iptPointerManager(app.UIFigure,'enable');
set(app.UIFigure,'WindowButtonMotionFcn',@(~,~)NaN)
Method 2: Assign a WindowButtonMotion to the figure
As Mohammad Sami suggested, the WindowButtonMotion function is assigned in AppDesigner > Designer View > in the Component Browser select the figure handle > callback > WindowButtonMotionFcn. Key components
- app.UIAxes - handle to the app's axes
- app.UIFigure - handle to the app's figure
- app.CurrentPositionEditField - handle to the text box
- UIFigureWindowButtonMotion() - See instructions above.
function UIFigureWindowButtonMotion(app, event)
cp = app.UIFigure.CurrentPoint;
isInAxes = cp(1) >= app.UIAxes.Position(1) && ...
cp(1) <= sum(app.UIAxes.Position([1,3])) && ...
cp(2) >= app.UIAxes.Position(2) && ...
cp(2) <= sum(app.UIAxes.Position([2,4]));
set(app.CurrentPositionEditField, 'Value',...
sprintf('%.2f, %.2f', app.UIAxes.CurrentPoint(1,1:2)))
set(app.CurrentPositionEditField, 'Value', '')