I'd like to declare an empty vector that accepts insertion of user-defined types. In the following examples node
is a type I've defined with classdef node ...
The following code is rejected by the Matlab interpreter because the empty vector is automatically initialized as type double, so it can't have a node
inserted into it.
>> a = [];
>> a(1) = node(1,1,1);
The following error occurred converting from node to double:
Conversion to double from node is not possible.
The code below is accepted because the vector is initialized with a node
in it, so it can later have nodes inserted.
>> a = [node(1,1,1)];
>> a(1) = node(1,2,1);
However, I want to create an empty vector that can have nodes inserted into it. I can do it awkwardly like this:
>> a = [node(1,1,1)];
>> a(1) = [];
What's a better way? I'm looking for something that declares the initial type of the empty vector to be node
. If I could make up the syntax, it would look like:
>> a = node[];
But that's not valid Matlab syntax. Is there a good way to do this?
Empty object can be created by
A = MyClass.empty;
It works with your own class, but also with Matlab's class such as
A = int16.empty;
This method is able to create multi-dimensional empty objects with this syntax
A = MyClass.empty(n,m,0,p,q);
as long as one dimension is set to zero.
See the doc.
You don't specify what your class contains, but yes, generally speaking it is possible to use array creation functions such as zeros
, ones
, and others for user-defined classes as well.
For in-built classes, you might have a call like
A = zeros(2,3,'uint8');
to create a 2-by-3 matrix of zeros of datatype uint8
. The similar syntax can also be applied for appropriate types of user-defined classes, for instance:
A = zeros(2,3,'MyClass');
where 'MyClass'
is the name of your class, or by giving an example:
p = MyClass(...);
A = zeros(2,3,'like',p);
The source for this information, along with a specification of how to implement support for array creation funtions in user-defined classes may be found here.
A call such as zeros(0,0,'MyClass')
would then produce an empty vector of type MyClass
.