MATLAB Object-Oriented Programming

(Joyce) #1

ClassName.PropName


For example, to use the NamedConst class defined in the previous section, reference the
constant for the degree to radian conversion, R:


radi = 45*NamedConst.R


radi =


0.7854


Constants In Packages


To create a library for constant values that you can access by name, first create a package
folder, then define the various classes to organize the constants. For example, to
implement a set of constants that are useful for making astronomical calculations, define
a AstroConstants class in a package called constants:


+constants/@AstroConstants/AstroConstants.m


The class defines a set of Constant properties with values assigned:


classdef AstroConstants
properties (Constant)
C = 2.99792458e8 % m/s
G = 6.67259 % m/kgs
Me = 5.976e24 % Earth mass (kg)
Re = 6.378e6 % Earth radius (m)
end
end


To use this set of constants, reference them with a fully qualified class name. For
example, the following function uses some of the constants defined in AstroContants:


function E = energyToOrbit(m,r)
E = constants.AstroConstants.G constants.AstroConstants.Me m ...
(1/constants.AstroConstants.Re-0.5
r);
end


Importing the package into the function eliminates the need to repeat the package name
(see import):


function E = energyToOrbit(m,r)
import constants.;
E = AstroConstants.G
AstroConstants.Me m ...


Define Class Properties with Constant Values
Free download pdf