Go to content Go to navigation Go to search

xeno
form

Category

Search


Links

Things that MATLAB has: Better Object Orientation · 2006-12-13

Earlier, I complained that MATLAB’s Object Orientation was lacking and suggested an improvement. As it turns out, MATLAB already has an extremely similar mechanism to the one I suggested, but has not documented it. The mechanism has existed since at least 7.3 (R14.3), but has several changes in R2006b.

Class Definition Syntax

The simplest class definition is:

 classdef myclass
    <statement-1>
    <statement-2>
    .
    .
    .
    <statement-N>
 end

Generally, the statements inside of the class will be method and field declarations, but any valid MATLAB is valid within the class definition.

This syntax is new as of R2006b. In R2006a and R14.3, classdef must be replaced with class

As before, m-files with class definitions must be placed in directories named @classname For example, an m-file named myclass.m might define a class myclass by opening the file with classdef myclass, but to be recognized as a class, myclass.m must be in a directory called @myclass on the MATLAB path.

Objects

More information forthcoming.

Field and Method Definition Syntax

More information forthcoming.

Encapsulation

This OO API supports fine-grained access controls (public, private, protected) for both fields and methods. More information forthcoming.

Inheritance

This OO API simplifies inheritance. Suppose myclass should inherit from baseclass. When defining myclass, we write:

 classdef myclass<baseclass
    <statement-1>
    <statement-2>
    .
    .
    .
    <statement-N>
 end

The only change from the standard class definition is the addition of baseclass to the class definition line.

Lazy Copy

Like variables passed into and returned from functions, MATLAB implements lazy copy when assigning values to class fields. For example,

 >> a = rand(1000);
 >> x = myclass();
 >> y = myclass();
 >> x.data = a;
 >> y.data = a;

This snippet requires enough memory to hold a, (plus some small overhead to hold the class data for x and y) but does not copy a unless a, x.data, y.data is modified. Hence the above snippet will require roughly only 8MB of memory rather than 24MB.

More Information

I am preparing longer documentation and will post it when complete. For longer examples, see the implementations of memmapfile and timeseries in MATLAB.

The structure of the above documentation is borrowed from the Python Tutorial’s chapter on classes.