How to call xlim and ylim after the most recent zoom?

13 views (last 30 days)
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.

Accepted Answer

Luna
Luna on 5 Sep 2019
Edited: Luna on 5 Sep 2019
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 :)
  2 Comments
Edward Huang
Edward Huang on 6 Sep 2019
Edited: Edward Huang on 6 Sep 2019
Thanks! My attempt was actually quite similar to your first approach, but the actionpostcallback seemed to fail to capture the values resulting xlim/ylim as undefined variables. I have tried your code and it works as a standalone method. I guess my issue involves the calling of those values from another function as well.
Thanks again!
Luna
Luna on 9 Sep 2019
Your welcome :)
If you want to access xlim/ylim values from another function, you should assign those values to an object property. This way you can reach xlim and ylim from another function.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!