Search code examples
matlaboopdata-structuresstatic-variables

Making a data structure available to all instances of a class?


I have a node data structure that represents nodes in a binary tree. I have some data that is relevant to the entire tree and rather than storing copies of it in each node, I just store indices in nodes that I use to access this global data. So my Node class has a constant property TreeData that contains the data I want available to all nodes:

classdef Node

    properties (Constant)
        treeData = TreeData
    end

    ...
    ...
end

with TreeData being defined as

classdef TreeData < handle
    properties
        s
        w
    end
end

This works fine, however its a nuisance having an entire extra class (TreeData) just to define two variables that should be accessible to all the nodes. So is there a better way of doing this? In another language I would just declare a static variable in the Node class to hold this data but in MATLAB it seems like you need getters and setters for static variables, which would end up leading to even more code having to be written than this TreeData class.

I don't just want something that works, I already have that, I'm looking for the most efficient/best-practice way to make a data structure available to all instances of a class in MATLAB.


Solution

  • The easiest way might be to just define a global variable. If you use a long enough name, there's a good chance you will never have a naming conflict. Simple, yes. Best practice, no.

    Matlab does have static-like variables, but they use the keyword persistent. They are local to the function where they are declared, but their values persist in memory between calls to the function. It's similar to how some other languages allow you to create static local variables for a function.

    It's hard to say what the best solution is for your situation without knowing how you are using this variable. If the variable is a counter, you could create an adjustCounter function that accepts an amount to adjust the counter and returns the new value. Getting the counter value is simply a matter of telling it to adjust by 0.

    Here is another similar question with several different suggested solutions.