Defining Named Constants

Creating a Class for Named Constants

There are situations where it is useful to define a collection of constants whose values can be accessed by name. To do this, create a class having properties with their Constant attribute set to true. Note that setting the Constant attribute to true effectively sets the SetAccess to private, so that the values of the properties cannot be changed outside of the class. You might define a package of classes defining various sets of constants and import these classes into any function that needs them.

A Package for Constants

To create a library for constant values that you can, first create a package directory, and then define the various classes to organize the constants you want to provide. For example, to implement a set of constants used for making astronomical calculations, you can define a AstroConstants class in the Constants package:

+Constants/@AstroConstants/AstroConstants.m

The class defines on a set of Constant properties with initial values assigned.

classdef AstroConstants
   properties (Constant = true)
   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, you would need to 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

Note that you cannot import class properties. Therefore, you must use the fully qualified class name to reference constant properties.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS