Search code examples
matlabooppropertiessubclassingundocumented-behavior

Attaching custom data (string tag) to a MATLAB cfit object


I have a code where cfit objects are passed back and forth between functions\classes and I would like to have a "tag" that contains some information about my fit (i.e. its name), such that I instantiate it at some point and can access it later whenever it's needed.

Ideally, this would be right inside the object, so that whenever I need to access the information, it's available without the need to drag around (or in appdata) additional vectors\cells.

Attempts & Thoughts

Normally, one would simply subclass cfit and add a property that contains this data. However, the declaration of cfit (see below) tells us that it is Sealed, and therefore cannot be subclassed.

classdef (Sealed = true) cfit < fittype

Alternatively, we could try to "hijack" some property that is not used by the current objects and use it to store the required data (not that it's a technical problem, but this is equivalent to ignoring the developers' warnings that these properties shouldn't be touched).

Moreover, from the above classdef we also learn that this is a subclass of fittype which may have some properties\methods we could use for this purpose.

Finally, the question remains - what is the best place to save my additional bit of data, so that it is both convenient to set\get (convenient means that if I want to access it inside a loop, I don't have to use eval()), and doesn't interfere with the normal operation of cfit objects?


Solution

  • One way that seems to work is by accessing the .p structure of a cfit object and adding whatever to it:

    Before:

    >> F378
    
    F378 = 
    
         Shape-preserving (pchip) interpolant:
           F378(x) = piecewise polynomial computed from p
         Coefficients:
           p = coefficient structure
    
    >> F378.p
    
    ans = 
    
          form: 'pp'
        breaks: [1x40 double]
         coefs: [39x4 double]
        pieces: 39
         order: 4
           dim: 1
    

    After F378.p.tag = '3.78';:

    F378.p
    
    ans = 
    
      form: 'pp'
    breaks: [1x40 double]
     coefs: [39x4 double]
    pieces: 39
     order: 4
       dim: 1
       tag: '3.78'
    

    I found this from the following error:

    Error using cfit/subsref (line 18)
    The name 'probnames' is not a coefficient or a problem parameter. You can only use dot 
    notation to access the coefficients and problem parameters of a cfit or sfit, for example 
    'f.p'.
    
    For the current object the properties you can access like this are:
    
    p
    

    Caution is advised: I did not test whether this solution interferes with normal operation.