MATLAB: How to call xlim and ylim after the most recent zoom

xlimylim;zoom

I am working on a small program and would like to realize the following feature:
After zooming in/out, I want to store the current (the most recent one) xlim and ylim values, which can be used in another function.
I was trying to use 'ActionPostCallback' but it was not successful. Any idea that how I should approach this? Even some pseudo codes will be much appreciated.
Thank you in advance.

Best Answer

Hello,
Try this:
hFig = figure;
hAxis = axes(hFig);
hPlt = plot(hAxis,rand(100,1));
zoomObj = zoom(hFig);
set(zoomObj,'ActionPostCallback', @zoomChanged);
function zoomChanged(~,AxisStruct)
xLimValues = get(AxisStruct.Axes,'XLim'); % you may want to save that into a handles struct of your gui to access it from another function

yLimValues = get(AxisStruct.Axes,'YLim');
end
Or you may want a class definition for that to get variables outside. Here:
classdef zoomChangeEvent < handle
properties
xLims
yLims
end
methods
function obj = zoomChangeEvent(obj)
hFig = figure;
hAxis = axes(hFig);
hPlt = plot(hAxis,rand(100,1));
zoomObj = zoom(hFig);
set(zoomObj,'ActionPostCallback', @obj.zoomChanged);
end
function zoomChanged(obj,~,AxisStruct)
obj.xLims = get(AxisStruct.Axes,'XLim') % you may want to save that into a handles struct of your gui to access it from another function
obj.yLims = get(AxisStruct.Axes,'YLim')
end
end
end
Just save the function and call it like below:
myZoomEvent = zoomChangeEvent
While constructing the object myZoomEvent, it will plot you some random data. Just play around with cursor and see it will print you the object's xLim and yLim properties.
The main difference between 1st and 2nd solution:
Both works when you clicked on it. Since you can't define a return value on callback functions, 1st solution tells you that: "What happens inside the function, stays inside the function."
On the other hand 2nd solution passes the object reference into zoomChanged callback function. So you can access the values via object properties you have assigned with dot notation.
Hope those will be helpful :)