let’s assume the following easy example:
f = figure;
plot(-10:10, (-10:10).^3, '*-r');
x = 1;
y = 1;
set(f, 'ResizeFcn', {@resizeCallback2, x, y});
while 1
[x, y, button] = ginput(1);
if(button ~= 1)
break;
end
set(f, 'ResizeFcn', {@resizeCallback2, x, y});
end
%%--------------------------
function resizeCallback2(hFig, ~, foo, bar)
foo
bar
end
Is there any easier way to always pass the ACTUAL* values for x and y to the callback function instead of having to always update it in the loop?
Thanks!
It looks like you are trying to store the value of a mouse click position, and then use those values as a part of the resize function (which would be called at a later time). There are a few changes that I would make.
First, instead of the
whileloop, use another callback to capture the mouse click. For example, you could use the figureButtonDownFcncall back to trigger a function which was designed to capture the mouse position into some location.Second, there are better ways to store the mouse position, and the right way will depend on your skill level and the needs of your program. Some of these methods of storing data are:
In the arguments to another callback, like you are doing now. This is pretty painful, but it probably works. So you could keep it if it is good enough for your needs.
The ‘userdata’ field in most Matlab objects. A few people have brought this up, and it will work fine. I don’t like to rely on this because I’m always afraid that some other tool will also want to use the userdata field, and the tools will overwrite data.
A
globalvariable value. I don’t like to use globals either, for the same reason I don;t like to use theuserdatafield. Butglobalsare sometimes the best solution anyway. This is probably the easiest, lowest effort solution to your problem if you only have one figure at a time. (Multiple figures would drive you towards theuserdatasolution as the easiest solution.)Provide a
handleclass to store some data (i.e. x and y) and give a copy of that class to each of the two callbacks (ButtonDownFcnandResizeFcn). This allows the two functions to pass data, without polluting anyone else’s namespace. This is my favorite solution to this sort of problem, so I’ll give it a more detailed description below.To execute option (4) above would need a class to store the data that looks something like this:
Note that since
ApplicationDataextendshandle, Matlab treats it as a pass-by-reference object, which is useful to us.Then you can create an instance of this class, and give it to each callback function.
Where
mouseClickCapturelooks something like this:And your
resizeCallback2looks something like this: