Search code examples
variablesmatlabcommentsworkspace

How to comment on MATLAB variables


When I´m using MATLAB, sometimes I feel the need to make comments on some variables. I would like to save these comments inside these variables. So when I have to work with many variables in the workspace, and I forget the context of some of these variables I could read the comments I put in every one of them. So I would like to comment variables and keep the comments inside of them.


Solution

  • While I'm of the opinion that the best (and easiest) approach would be to make your variables self-documenting by giving them descriptive names, there is actually a way for you to do what you want using the object-oriented aspects of MATLAB. Specifically, you can create a new class which subclasses a built-in class so that it has an additional property describing the variable.

    In fact, there is an example in the documentation that does exactly what you want. It creates a new class ExtendDouble that behaves just like a double except that it has a DataString property attached to it which describes the data in the variable. Using this subclass, you can do things like the following:

    N = ExtendDouble(10,'The number of data points')
    N = 
    The number of data points
         10
    

    and N could be used in expressions just as any double value would. Using this example subclass as a template, you could create "commented" versions of other built-in numeric classes, with the exception of those you are not allowed to subclass (char, cell, struct, and function_handle).

    Of course, it should be noted that instead of using the ExtendDouble class like I did in the above example, I could instead define my variable like so:

    nDataPoints = 10;
    

    which makes the variable self-documenting, albeit with a little more typing needed. ;)