What are brackets []
doing in Matlab, if not filled with numbers?
Let's assume we have some objects obj1
, obj2
and obj3
of a ClassA
. Apparently it's possible to combine them with brackets in a .. don't know, what it actually is
objects = [obj1 obj2 obj3];
>> class(objects)
ans =
ClassA
>> objects
objects =
1x3 ClassA handle
Properties:
name
...
objects = []; objects(end+1) = current_obj;
does not workobjects{end+1} = current_obj;
creates a cellWhen using the []
notation again on a field it gives
K>> [objects.name]
ans =
Object1Object2Object3
K>> class([objects.name])
ans =
char
[obj1 obj2 obj3]
is an array of objects of class ClassA
, just like [1 2 3]
is an array of numbers.
If you type a = []; a(2) = 1
, MATLAB will return a
as [0 1]
, in other words it will fill any unspecified elements of a
with a default element which, in the case of numbers, is zero.
When you type objects = []; objects(2) = current_obj
, MATLAB similarly attempts to put current_obj
in the requested position 2 of objects
, and then to fill the unspecified elements with default objects of class ClassA
. To do this, it calls the constructor of ClassA
, but you need to know that it calls the constructor with no input arguments.
Therefore, if you want to be able to support this sort of array filling with objects of your class, you need to implement the class constructor so that it will not error when called with zero input arguments. For example, you could simply check nargin
, and if it's zero, supply some default inputs, otherwise accept whatever inputs were provided.
By the way, by default []
is of class double
. If you want to create an empty array of class ClassA
, you can use objects = ClassA.empty
. empty
is a built-in method of all MATLAB classes. You may find that you avoid some errors by making sure that you don't accidentally attempt to concatenate double
s with objects of class ClassA
.