|
|||
Department of Engineering | |
University of Cambridge > Engineering Department > computing help > programs > matlab |
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.
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.
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+colour3will 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').
| computing help | Matlab | Single-file O-O | |