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
A basic example
Let's define a basket class to store fruits and vegetables:
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
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
>> 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
The only operator that cannot be overloaded is the
Comments
There are no comments on this post so far. Write a comment.
