MATLAB Object-Oriented Programming

(Joyce) #1
dims = [varargin{2:end}];
r = zeros(dims,'Color');
for k = 1:prod(dims)
r(k) = Color('RGB',randi(varargin{1},[1,3]));
end
end
end
end
end

Prototype Object Method Implementation

The objective of a method that returns an array of objects that are “like a prototype
object” depends on the requirements of the class. For the Color class, the zeroLike
method creates objects that have the ColorSpace property value of the prototype object,
but the ColorValues are all zero.

Here is an implementation of a zerosLike method for the Color class. This
implementation:


  • Defines the zerosLike method as Hidden

  • Returns a scalar Color object if the call to the zeros function has no dimension
    arguments

  • Returns an empty array if the call to the zeros function has any dimension arguments
    that are negative or equal to 0.

  • Returns an array of Color objects of the dimensions specified by the call to the zeros
    function.


classdef Color
...
methods (Hidden)
function z = zerosLike(obj,varargin)
if nargin == 1
% For zeros('like',obj)
cSpace = obj.ColorSpace;
z = Color;
z.ColorSpace = cSpace;
elseif any([varargin{:}] <= 0)
% For zeros with any dimension <= 0
z = Color.empty(varargin{:});
else
% For zeros(m,n,...,'like',obj)
if ~isscalar(obj)
error('Prototype object must be scalar')
end
obj = Color(obj.ColorSpace,zeros(1,3,'like',obj.ColorValues));

9 Methods — Defining Class Operations

Free download pdf