Get Matlab data tip value in custom context menu

65 Views Asked by At

In Matlab, I would like a context menu to open when I right-click on a data point in a plot. The selected action should call a function where I would like to access the coordinates of the data point for further processing.

The Matlab example is:

cm = uicontextmenu(fig);
m = uimenu(cm);
m.Text = "Function description";
m.MenuSelectedFcn = @(src,event)myFunction(src,event);

function myFunction(src,event)
...
end

plot(x, y, "ContextMenu", cm);

This works as expected in that myFunction is called when I right click on a data point and click on the action in the context menu. However, I cannot access the x,y values of the data point within myFunction.

1

There are 1 best solutions below

0
Wolfie On

If you really want to implement a custom function then you can use the CurrentPoint property of the current axes, so your function would be something like

function myFunction(src,event)
    cp = get( gca, 'CurrentPoint' );
    x = cp(1,1);
    y = cp(1,2);
    fprintf( 'x = %.2f, y = %.2f\n', x, y );
end

In use:

custom callback


However, the functionality you're describing can be achieved natively (without a custom callback) using the datatip cursor and the Export Cursor Data To Workspace... option.

Other advantages include

  • Easier to right click because you can do so anywhere with the data tip cursor enabled rather than having to hit the line exactly.
  • You can view and move the selected points before they're exported
  • You can select multiple points and they are all exported.

data tip

You have even more options using the in-built brushing tool, where you can brush areas of your data and then

  • You can export, copy, or display data in the command window
  • You can quickly highlight whole regions of data
  • Slightly more fiddly than the data tips as you have to right-click the actual brushed data to get the right click menu, the same as the custom callback.

brush