Search code examples
matlabbracketsnotation

What are brackets `[]` doing in Matlab, if not filled with numbers?


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
    ...
  1. Whats this called?
  2. How to iteratively build such thing?
    objects = []; objects(end+1) = current_obj; does not work
    objects{end+1} = current_obj; creates a cell
  3. How can one convert to this e. g. from a cell with objects?

When using the [] notation again on a field it gives

K>> [objects.name]

ans =

Object1Object2Object3

K>> class([objects.name])

ans =

char

Solution

  • [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 doubles with objects of class ClassA.