Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help >  programs >  matlab

Object-oriented programming with Matlab (pre-2008)

This file describes an old way of doing O-O in Matlab. I've left it online, though the newer (post-2008) way described on the Single-file O-O page is much the most preferred.

Why?

Object-oriented programming is a popular mode of working and is supported by Java, C++ and many other modern languages. It's claimed that it makes code easier to read and maintain. Furthermore, an object-oriented approach is in many cases more natural and appeals more to human cognition than other methodologies.

What?

In object-oriented programming you invent new types (called classes) designed to suit your task. These types are more sophisticated than simple variables or arrays - they can have functions (called methods) too. Just as you can create variables of a standard type (like a double in fortran) so in object-oriented programming you can create an object of a certain class. And you can redefine what '+' etc does when applied to these new objects. Some important object-oriented (O-O) concepts are The aim is to create objects that have tightly related parts but few connections with anything else. As an analogy consider a lightbulb: as long as it has a standard interface other components don't have to worry about how it's designed internally, and the lightbulb can easily be replaced by one that's internally very different.

Where?

The code for a matlab class has to go in a sub-folder called @class_name which has to be in a folder where matlab normally looks for functions. So on the Unix Teaching System, the code for a colour class could go in a ~/matlab/@colour folder.

How?

CUED's 2nd year C++ course mentions classes. The principles of Matlab's classes are similar - Mathworks' Tips for C++ and Java Programmers lists the main differences.

One function you must have is a class constructor which is called when an object is created. This function has to cope with being given some (or no) arguments, and being given an object. The constructor has the same name as the class. Here's a constructor for a colour class. It uses the class command to create objects. It goes in a file called colour.m

function c = colour(varargin)
%COLOUR Colour class constructor
switch nargin
       case 0
          % No argument - set default colour
          c.red = 0;
          c.green=0;
          c.blue=0;
          c = class(c,'colour');
       case 1
          % 1 argument - if it's a colour object, copy to a new object
          if (isa(varargin{1},'colour'))
            c = varargin{1};
          else
            % assume the arg is a number and set all the components
            c.red = varargin{1};
            c.green=varargin{1};
            c.blue=varargin{1};
            c = class(c,'colour');  
          end 
       case 3
          % 3 arguments. Assume that they're the red, green and blue values
          c.red =varargin{1} ;
          c.green=varargin{2};
          c.blue=varargin{3};
          c = class(c,'colour');
       otherwise
           error('Wrong number of input arguments')
       end
Another important method is display which is called when the object is output as text. Here's a display method for a colour class. It goes in a file called display.m. It produces output that's in the same form as standard MATLAB output: the variable name is displayed followed by an equal sign, then a blank line, then a new line with the values.
function display(c)
% COLOUR/DISPLAY
disp(' ');
disp([inputname(1),' = '])
disp(' ');
disp(['   ' 'Red=' num2str(c.red) ', Green=' num2str(c.green) ', Blue=' num2str(c.blue) ])
disp(' ');
If you create these 2 files now (remember, they need to go in the ~/matlab/@colour folder), you can test them by typing
   colour1=colour(1,2,3)
   colour2=colour(colour1)
   colour3=colour
(note that these lines don't end with semicolons, so the display method is called) and then
   colour4=colour(6,5)
which should print an error message because the number of arguments is wrong.

The Designing User Classes in MATLAB page has more details.

Class methods

Adding 2 of these colour objects together produces an error message, but you can make the '+' operator work with these new objects by creating a plus method. The following one produces a colour whose components are the average of the constituents' components. The code is written so that it will still work even if one of the operands is a number - the c1 = colour(c1) line has no effect if c1 is already a colour, but will convert c1 to a colour if it's a number.
function r = plus(c1,c2)
% COLOUR/PLUS  Implement '+' for colours.
c1 = colour(c1);
c2 = colour(c2);
r= colour ( (c1.red+c2.red)/2,(c1.green+c2.green)/2,(c1.blue+c2.blue)/2);
With this code installed as plus.m typing
  colour5=colour1+colour3
will produce a blend. If you want to be able to brighten a colour by a given factor, you could add a brighten method
function r = brighten(c,f)
% COLOUR/BRIGHTEN 
r= colour (c.red*f, c.green*f, c.blue*f);
and once you've installed it as brighten.m you can call colour5=brighten(colour5,3) to brighten colour5 by a factor of 3.

To find out which methods exist for a class, use the methods command - e.g. methods('colour').

When?

Not all tasks are suited to an object-oriented approach, but in a big project it's useful to be able to hide data, and keep data close to related routines. It also helps with name-clash issues. As in C++, it's possible to have 2 or more functions with the same name as long as they have different types of objects as arguments. The brighten function created above is invoked if the first argument is a colour object, otherwise the standard brighten function is called.
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: October 2001