As far as I know, the figure object doesn't expose this kind of information. Not even in its undocumented underlying Java
class. But I have an idea that may represent a nice workaround to this problem.
Use the following overload of the figure function:
figure(n) finds a figure in which the Number property is equal to n,
and makes it the current figure. If no figure exists with that
property value, MATLAB® creates a new figure and sets its Number
property to n.
in order to assign an "unique identifier" to every existing figure, and associate these identifiers to a datenum
value that represents the creation time:
% Initialize the lookup table somewhere in your code:
lookup_table = zeros(0,2);
% Together with a variable that stores the next unique identifier to be assigned:
next_id = 1;
% When you need to instantiate a new figure...
% 1) Retrieve the current datetime:
cdate = now();
% 2) Update the lookup table:
lookup_table = [lookup_table; next_id cdate];
% 3) Initialize the new figure:
figure(next_id);
% 4) Increment the next unique identifier:
next_id = next_id + 1;
Every row of the lookup table will then contain an unique figure identifier and its respective creation date.
Everything else is pretty easy to handle. When you want to query a figure uptime... find its unique identifier in the lookup table and subtract the current time (obtained using the now()
command) to the creation time. I recommend you to to define a CloseRequestFcn
handle for every figure you create, so that when a figure is closed, you can update the lookup_table
and remove it. The identifier you assigned to a specific figure can be retrieved using its Number
property. Here is a full working implementation:
global lookup_table;
global next_id;
lookup_table = zeros(0,2);
next_id = 1;
f1 = create_figure();
f2 = create_figure();
pause(10);
f1_ut = get_figure_uptime(f1)
f2_ut = get_figure_uptime(f2)
function f = create_figure()
global lookup_table;
global next_id;
cdate = now();
f = figure(next_id);
f.CloseRequestFcn = @update_lookup_table;
lookup_table = [lookup_table; next_id cdate];
next_id = next_id + 1;
end
function ut = get_figure_uptime(f)
global lookup_table;
tn = now();
tc = lookup_table(lookup_table(:,1) == f.Number,2);
if (isempty(tc))
ut = -1;
else
ut = etime(datevec(tn),datevec(tc));
end
end
function update_lookup_table(f,~)
global lookup_table;
lookup_table(lookup_table(:,1) == f.Number,:) = [];
delete(f);
end
Alternatively, as you suggested in your comment, you can add a property to every figure you create in which its creation time can be stored. It's much more immediate and eliminates the need to handle a lookup table. For this, just use the addprop functon as follows:
cdate = now();
f = figure();
addprop(f,'CreationTime');
f.CreationTime = cdate;