MATLAB: How to use the “ButtonDownFcn” for a plot in App Designer

appbuttondownfcncallbackclickdesignerplotuiaxes

Best Answer

You are correct that there is no "ButtonDownFcn" for a UIAxes. Thus, stick to using the "ButtonDownFcn" with your plot object.
To start, create a plot in your app's StartupFcn and define the plot's "ButtonDownFcn" with an associated callback function:
The key here is _where _you define this callback function. If you simply add a new public/private function in Code View, the plot object will be unable to find the function when the callback is triggered, and you will get an error. This is because your app is set up as a class in App Designer, and thus, your callback will be defined as a class method, not an ordinary function.
The easiest alternative is to define your callback function as a nested function, located inside the StartupFcn. Check out the example below, in which I plot a parabola. If a user clicks on the parabola, a nested callback will be triggered that adds the x- and y-coordinates to a UITable, which lists the coordinates of all points that have been clicked so far.
function startupFcn(app)
% create plot with line object
x = linspace(-5,5);
y = -1 * x.^2;
plot(app.UIAxes,x,y,'ButtonDownFcn',@mouse_click);
% define callback as nested func
function mouse_click(~,eventData)
% get coordinates of click
coords = eventData.IntersectionPoint;
% do something with the coordinates (e.g. add coordinates to table)
app.UITable.Data(end+1,:) = [coords(1),coords(2)];
end
end
To create run this example yourself, simply add a UIAxes and a UITable to your figure in the Design View of App Designer. Then add the code above to a StartupFcn.
Also, for an alternative method of getting clicked points, see this related MATLAB Answers post: