If I get coordinates via
coords = get(0,'PointerLocation');
How can I convert them into points gotten via ginput
?
i.e, I would like to get the same values from
coords = get(0,'PointerLocation');
coords=someConversion(coords);
As I would have gotten by calling
coords=ginput(1);
And clicking inside the figure in the same spot as the mouse was in the previous bit of code.
You can get the figure's position using
getpixelposition(gcf)
and then subtract the first 2 elements (x,y of the lower-left corner) from the PointerLocation to get the relative figure location.For more complex transformation (e.g., relative to some internal panel or axes) you may possibly need to recursively fetch the relative positions of the sub-components. Look at pixelposition.m or moveptr.m for some examples.
Here's an example of how you can do this conversion...
Let's say you have a figure, and that figure contains an axes object with handle
hAxes
. Using the functionginput
would allow you to select points within the axes. To get an equivalent set of points fromget(0, 'PointerLocation')
, which gives coordinates in relation to the screen, you have to account for the figure position, axes position, axes width/height, and axes limits.Doing this is tricky because you want to have the position measures in the same units. If you want to compute everything in units of pixels, this means you'd have to set the
'Units'
properties of the objects to'pixels'
, get the positions, then set the'Units'
properties back to what they previously were. I usually make my own functionget_in_units
to do this part:Using the above function, you can make another function
get_coords
which gets the screen coordinates and converts them to axes coordinates:The resulting
coords
should be close to those you would get from usingginput
. Note that if the axes object is nested within any uipanel objects in the figure, you will have to account for the panel positions as well.Example:
To illustrate the behavior of the above code, here's a neat little example. After creating the above functions, create this third function:
Then run the following code:
And when you move the mouse pointer over the figure axes, you should see a trail of red asterisks being plotted behind it, like so: