Search code examples
matlabundocumented-behavior

Matlab figure 'age'


Here's a question for 'experts in the less documented part of Matlab': is there a (undocumented?) way to determine how long a figure has been open for (i.e. the 'age' of the figure)?

figure; spy;
myfig=gcf;
age=get_age() %shoud output age of figure in some format

Solution

  • You can use the following mechanism:

    First, create a small Matlab function as follows, that attaches the CreationTime property to a figure:

    function setCreationTime(hFig,varargin)
       hProp = addprop(hFig,'CreationTime');
       hFig.CreationTime = now;
       hProp.SetAccess = 'private'; %make property read-only after setting its initial value
    
       hProp = addprop(hFig,'Age');
       hProp.GetMethod = @(h,e) etime(datevec(hFig.CreationTime), clock); %compute on-the-fly
       hProp.SetAccess = 'private'; %make property read-only
    end
    

    Now assign this function as the default CreateFcn callback function for all new figures from now on:

    set(0,'DefaultFigureCreateFcn',@setCreationTime)
    

    That's it - you're done!

    For example:

    >> newFig = figure;
    >> newFig.CreationTime
    ans =
          737096.613706748
    
    >> ageInDays = now - newFig.CreationTime
    ageInDays = 
           0.01625078368466347
    >> ageDuration = duration(ageInDays*24,0,0)
    ageDuration = 
      duration
       00:23:24
    >> ageString = datestr(ageInDays, 'HH:MM:SS.FFF')
    ageString = 
        '00:23:24.068'
    
    >> ageInSecs = newFig.Age
    ageInSecs =
        1404.067710354923808