How do I keep a handle and use FINDOBJ to get a handle again?
显示 更早的评论
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.
采纳的回答
更多回答(2 个)
Matt Fig
2011-2-17
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.
Jiro Doke
2011-2-17
0 个投票
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Creating, Deleting, and Querying Graphics Objects 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!