Blog
Matlab syntax tricks

By Raphaël - December 18th, 2016

Matlab

0 Comment

Packages
The !(bang) operator

Operator overload

My favourite syntax trick is to overload operators. One can indeed redefine - pretty easily by the way - the behavior of the almost every operators, event the most basic ones like +, . or =. The limitation is that you can overload operators for your own objects, not Matlab's built-in objects like numbers or strings.

A basic example

Let's define a basket class to store fruits and vegetables:

basket.m
classdef basket < handle
   
    % --- Properties ----------------------------
    properties
        
        fruits = {};
        vegetables = {};
        
    end
    
    % --- Methods -------------------------------
    methods
        
        % The clas constructor (empty)
        function this = basket(), end
        
    end
    
end

And let's define two baskets:

% Define the first basket
A = basket;
A.fruits = {'apple', 'banana', 'orange'};
A.vegetables = {'avocado', 'broccoli', 'carrot'};

% Define the second basket
Z = basket;
Z.fruits = {'watermelon'};
Z.vegetables = {'yam', 'zucchini'};

So far, so good. Now let's modify the basket class to add a method plus:

basket.m
classdef basket < handle
   
    % --- Properties ----------------------------
    properties
        
        fruits = {};
        vegetables = {};
        
    end
    
    % --- Methods -------------------------------
    methods
        
        % The clas constructor (empty)
        function this = basket(), end
        
        % Overload the + operator
        function B = plus(this, other)
        
           B = basket();
           B.fruits = [this.fruits other.fruits];
           B.vegetables = [this.vegetables other.vegetables];
            
        end
        
    end
    
end

This method overloads the + operator, and we can now concatenate the contents of the baskets with +:

>> Final = A+Z

Final = 

  basket with properties:

        fruits: {'apple'  'banana'  'orange'  'watermelon'}
    vegetables: {'avocado'  'broccoli'  'carrot'  'yam'  'zucchini'}

Going further

The complete list of overloadable operators and the associated method names are available in the documentation. Interestingly, the subsref method handles indexing, more precisely the A(i), A{i} and A.i syntaxes. The subsasgn and subsindex methods can also be really interesting in some cases, so you definitively should check their documentation.

The only operator that cannot be overloaded is the ! (bang) operator. We will cover it in detail on the next section.

Packages
The !(bang) operator

Comments

There are no comments on this post so far. Write a comment.