MATLAB Object-Oriented Programming

(Joyce) #1

function z = zeros(varargin)
if (nargin == 0)
% For zeros('Color')
z = Color;
elseif any([varargin{:}] <= 0)
% For zeros with any dimension <= 0
z = Color.empty(varargin{:});
else
% For zeros(m,n,...,'Color')
% Use property default values
z = repmat(Color,varargin{:});
end
end
end
end


The zeros method uses default values for the ColorValues property because these
values are appropriate for this application. An implementation of a ones method can set
the ColorValues property to [1,1,1], for example.


Suppose that you want to overload the randi function to achieve the following objectives:



  • Define each ColorValue property as a 1-by-3 array in the range of 1 to a specified
    maximum value (for example, 1–255).

  • Accommodate scalar, empty, and multidimensional array sizes.

  • Return an array of Color objects of the specified dimensions, each with random
    ColorValues.


classdef Color
...
methods (Static)
function r = randi(varargin)
if (nargin == 0)
% For randi('ClassName')
r = Color('RGB',randi(255,[1,3]));
elseif any([varargin{2:end}] <= 0)
% For randi with any dimension <= 0
r = Color.empty(varargin{2:end});
else
% For randi(max,m,n,...,'ClassName')
if numel([varargin{:}]) < 2
error('Not enough input arguments')
end


Class Support for Array-Creation Functions
Free download pdf