MATLAB Object-Oriented Programming

(Joyce) #1
NoteThe AllowedSubclasses and the InferiorClasses attributes require an
explicit specification of a cell array of meta.class objects as their values. You cannot
use expressions to return these values.

See “Attribute Specification” on page 5-22 for more information on attribute syntax.

Expressions That Specify Default Property Values

Property definitions allow you to specify default values for properties using any
expression that has no reference to variables. For example, VectorAngle defines a
constant property (Rad2Deg) and uses it in an expression that defines the default value of
another property (Angle). The default value expression also uses a static method
(getAngle) defined by the class:

classdef VectorAngle
properties (Constant)
Rad2Deg = 180/pi
end
properties
Angle = VectorAngle.Rad2Deg*VectorAngle.getAngle([1 0],[0 1])
end
methods
function obj = VectorAngle(vx,vy)
obj.Angle = VectorAngle.getAngle(vx,vy);
end
end
methods (Static)
function r = getAngle(vx,vy)
% Calculate angle between 2D vectors
cr = vx(1)*vy(1) + vx(2)*vy(2)/sqrt(vx(1)^2 + vx(2)^2) * ...
sqrt(vy(1)^2 + vy(2)^2);
r = acos(cr);
end
end
end

You cannot use the input variables to the constructor to define the default value of the
Angle property. For example, this definition for the Angle property is not valid:

properties
Angle = VectorAngle.Rad2Deg*VectorAngle.getAngle(vx,vy)
end

6 Defining and Organizing Classes

Free download pdf