How do I keep a handle and use FINDOBJ to get a handle again?
Show older comments
Handles have to be one of the most frustrating data objects to deal with in MATLAB.
I have created a class in which I want to store a reference to a figure (a window) that has been created. While I can live with a scalar double returned by the gcf() function and saving that somewhere in my object - as a double and not as a handle - why does any effort to recover that handle using findobj(123.0045) or any other such function with a number passed to it appear to only return with an error telling me I have an invalid handle reference.
So, what the devil IS a valid reference to a handle? How can I keep a reference to it reliably without having to call gcf or gca every time I want a particular handle that works?
NOTE EDIT to title by Doug to reflect nature of actual question. Slight mods to text of question for clarity.
Accepted Answer
More Answers (2)
Matt Fig
on 17 Feb 2011
The FINDOBJ function finds the handle which fits the property/value pairs passed to it. It looks like you are passing a handle (123.0045) to FINDOBJ, which is bizarre because you have the handle already - what is the point? This is equivalent to doing:
ax = gca % Get the handle to current axes.
ax_handle = findobj(ax) % Get the handle to current axes.
You can store any handle structure you want in the root userdata. This is accessible from anywhere. For example:
clear all,close all,clc % Don't do this if your stuff isn't saved!
S.fh = gcf;
S.ax = gca;
S.L(1) = plot(1:10)
hold on
S.L(2) = plot(rand(1,4));
set(0,'userdata',S)
Now from any workspace whatsoever, you can call
S = get(0,'userdata');
and use the handles. Just don't forget the update the userdata property if new handles are then added to S, or if an object is deleted.
1 Comment
Chris Shannon
on 18 Feb 2011
Jiro Doke
on 17 Feb 2011
0 votes
What Matt and Matt said. Plus, I would emphasize again:
Never ever ever use the actual number to refer to the handle. Instead, save the scalar double number as a variable and just use the variable in the rest of your code.
1 Comment
Chris Shannon
on 18 Feb 2011
Categories
Find more on Graphics Object Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!