MATLAB Object-Oriented Programming

(Joyce) #1
The following definition of the TemperatureData class implements a specialized version
of plot to graph temperature data. The class plot method supports a variable number of
input arguments to allow an axes handle as the first argument:

plot(obj)
plot(ax,obj)

obj is an instance of the TemperatureData class and ax is an axes handle.

MATLAB calls the plot method in both cases because the TemperatureData class
specifies the matlab.graphics.axis.Axes as inferior.
classdef (InferiorClasses = {?matlab.graphics.axis.Axes}) TemperatureData
properties
Time
Temperature
end
methods
function obj = TemperatureData(x,y)
obj.Time = x;
obj.Temperature = y;
end
function plot(varargin)
if nargin == 1
obj = varargin{1};
plot(obj.Time,obj.Temperature)
elseif nargin == 2
ax = varargin{1};
obj = varargin{2};
plot(ax,obj.Time,obj.Temperature)
elseif nargin > 2
ax = varargin{1};
obj = varargin{2};
plot(ax,obj.Time,obj.Temperature,varargin{3:end})
end
datetick('x')
xlabel('Time')
ylabel('Temperature')
end
end
end

The following call to plot dispatches to the TemperatureData plot method, not the
built-in plot function, because the TemperatureData object is dominant over the axes
object.

x = 1:10;
y = rand(1,10)*100;
ax = axes;
td = TemperatureData(x,y);
plot(ax,td)

9 Methods — Defining Class Operations

Free download pdf