MATLAB: How to create an array of class handles

classhandlevector

I'm a C++ developer and need to find an equivalent to a vector of class pointer: std::vector<MyClass*>
I have my Matlab classes inheriting handle already but what would be the appropriate container to use in Matlab for the vector part?
Thanks in advance.

Best Answer

It all depends...
  • Assuming you don't have inheritance, then you can simply create a matrix of your class objects. You can create the array of object any way you want, e.g:
objarray(1:10, 1:5) = MyClass; %creates a 10x5 array initialised with default value of MyClass
objarray(10, 5) = MyClass; %same
objarray(1:10, 1:5) = MyClass(somearg); %creates a 10x5 array initialised with constant MyClass object
objarray = [MyClass, MyClass, MyClass]; %create array by concatenation
objarray = [objarray; MyClass]; %add more elements
Now coming from a C++ background it may not be something you're aware of, but an array of object and a scalar object are exactly the same type and invoke the exact same constructor. In additions all methods of the class can be passed a scalar object or an object array. This is something that may trip you up as you may have designed your class to only work with scalar objects. See this doc and this doc for more on initialising object array, and this one for how to do it in the constructor.
  • If your class is not meant to be used as an array (you can actually prevent array creation), then you could simply store the individual objects in a cell array. The downside is that there is nothing preventing you to store non MyClass in the array.
  • If you have inheritance and MyClass is a base class for several derived classes which you want to be able to store in the array, then you need to derive your base class from matlab.mixin.hetergeneous and implement the required methods.