Loren on the Art of MATLAB

Turn ideas into MATLAB

Who, what, why, but not this 8

Posted by Loren Shure,

Dave Foti, who manages development of object oriented programming features in the MATLAB language, is back with a discussion of object parameters in methods.

A fairly frequent question from my colleagues and some of you is why MATLAB classes don’t have a keyword like “this” inside methods and support for the other behaviors found in languages with a “this” keyword. Having to declare the name of every object parameter to a method may be a minor inconvenience, but having to prefix properties with that object parameter is much more cumbersome. For example, consider the following Java method:

public int getArea() {
    return Width * Height;

In the MATLAB language, such a function would be written as something like:

type Rect/getArea
function A = getArea(R)
    A = R.Width .* R.Height;

While the above example looks simpler in Java, there are situations where implicit object arguments get in the way. Many functions such as binary operators work on multiple objects. When a function needs to work on data from multiple objects, languages with implicit object parameters can lead to an asymmetry in handling the different objects. For example, consider a Java intersect method to return the intersection of two input rectangles:

public Rect intersect(Rect B) {
    Rect C = new Rect();
    C.X = max(X, B.X);
    C.Y = max(Y, B.Y);
    C.Width = min(X+Width, B.X + B.Width) – C.X;
    C.Height = min(Y+Height, B.Y + B.Height) – C.Y;
    return C;

To restore some symmetry, sometimes I see the following pattern:

public Rect intersect(Rect that) {
    Rect other = new Rect();
    other.X = max(this.X, that.X);
    other.Y = max(this.Y, that.Y);
    other.Width = min(this.X+Width, that.X + that.Width) – other.X;
    other.Height = min(this.Y+Height, that.Y + that.Height) – other.Y;
    return other;

However, a MATLAB method naturally accesses all rectangles in the same manner:

type Rect/intersect
function C = intersect(A, B) 
    C.X = max(A.X, B.X);
    C.Y = max(A.Y, B.Y);
    C.Width = min(A.X+A.Width, B.X+B.Width) - C.X;
    C.Height = min(A.Y+A.Height, B.Y+B.Height) - C.Y;

Another important consideration for the MATLAB language is operators that work on objects and numbers or different kinds of objects. For example, a Rational number class may provide arithmetic operators that work on any combination of rational values and built-in numeric values.

x = Rational(5,7)
x = 

y = 3 .* x
y = 

z = x .* 3
z = 

t = y .* x
t = 

The Rational function times is called in all three multiplications above:

type Rational/times
function R = times(X,Y)
    if isa(X, 'Rational')
        if isa(Y, 'Rational')
            R= Rational(X.Numerator .* Y.Numerator, ...
                        X.Denominator .* Y.Denominator);
            if ~isnumeric(Y)
                error('Y must be a number.');
            R = Rational(X.Numerator .* Y, X.Denominator);
        if ~isnumeric(X)
            error('X must be a number.');
        R = Rational(X .* Y.Numerator, Y.Denominator);

In this example we can see the value of making all arguments explicit. It allows operators to work on a first double argument and a second Rational argument. It also reinforces the fact that functions inside the class can access private data and methods on any instance of the class. The times method is a method of the Rational class that works on one or more instances of Rational numbers. When it works on two Rational numbers to produce a new Rational result, there is nothing special about any one of these three instances.

MATLAB functions, methods, and variables share the same namespace. Object properties are scoped to the class of the object and their names can be the same as MATLAB keywords. While it would sometimes be more convenient, implicit references to an object parameter would also mean additional restrictions on property names and potential conflicts with function names.

I would be interested in hearing your thoughts on this subject. In your code, what is the relative frequency of methods that work on a single object versus multiple objects? How important is the convenience of implicit object access to you? Would you like a way to declare that a block of methods define access operations on an object and make the object implicit within these methods?

Get the MATLAB code

Published with MATLAB® 7.14


Comments are closed.

8 CommentsOldest to Newest

Jonas replied on : 1 of 8

When I have classes that implement set-methods for certain properties (such as auto-save), I like being able to write

prop = obj.prop;
% do some complex calculations with the property “prop”

% store the updated property value, trigger the set method
obj.prop = prop;

Malcolm Lidierth replied on : 2 of 8

In MATLAB OOP, I tend always to use “obj” also rather than “this”. It can be a problem debugging when I break that habit (similar to a problem some years ago when I struggled with 1 line of code that failed to compile but appeared correct. After many hours of head scratching, somebody kindly pointed out that the line was written in Pascal while the rest of the code was in Fortran).
Without adding “this” as a genuine keyword, adding an editor syntax highlighting option to colour “this” or “thisObj” could sometimes be useful.

xmo replied on : 3 of 8

I used to programming in C/C++, so to me the java version is more intuitive and concise. But that’s just my personal preference.
Another alternative is to introduce some new syntax in addition to the old style, e.g. “With” keyword in Visual Basic

Alexandre Kozlov replied on : 4 of 8

2 Malcolm: it really could be useful! And if MatLab will recognise that the first argument of a non static method is an object of this class, and propose its members in editor after typing a . – that will be really great.

Julian replied on : 5 of 8

On a related note, I always feel slightly surprised I have to provide the fully qualified name of a class constant even inside the classdef, e.g. thisclassname.CONSTANT. I kind of expect these constants to be in scope like in regular nested functions. PS. Alexandre’s idea re. editor treatment of 1st argument of non static method is a good one.

John replied on : 6 of 8

I like the MATLAB way myself. It makes it very clear where variables come from, whereas the implicit object can get a little confusing.

Wes replied on : 7 of 8

Explicitly typing ‘this’ doesn’t bother me too much, so I think that the best idea so far is Alexandre’s idea: for tab-completion to suggest members of the current class if you type ‘this.’ (or whatever you happened to name the instance argument).

A quick search of some of my codebases shows over 8000 lines of MATLAB code that contain ‘this.’ at least once. So with this feature, that’s many thousands of times less that somebody would have needed to type out, and occasionally misspell, the name of the member they were after.

This would be a killer feature, especially combined with two very easy fixes to the existing tab-completion functionality:
– Correct the capitalization of what you have typed so far to match the correct capitalization.
– Allow the up arrow to be pressed when at the top of the tab-completion box to wrap around to the bottom entry (and vice versa).

Andrey replied on : 8 of 8

Hi Loren,

I think that what bothers me and many other Matlab users is the fact that there is no good support of packages. Either the coder is forced to type package name each and every time he accesses it, or he must use import in each and every function.

Ideally, I would like to see an `import MyPackage` keyword once in a beginning of an .m file, and never again.

I guess that it has to do with the interpreter nature of Matlab, but then again, they solved it quite well in Python.

(Here is a better description – http://stackoverflow.com/questions/8883499/can-i-import-a-namespace-globally-without-explicitly-calling-import-in-each-and).