It is possible to create named constants as part of a class or package in MATLAB versions 7.6 (R2008a) and above.
The ability to create constant variables is not available in previous versions of MATLAB. To work around this, you can create a function with the same name as the constant that returns its value. For example, the following functoin returns the value of Planck's constant:
function h = planck
h = 6.626068e-34;
However, if you create a variable called "planck", it will shadow the function. This is also similar to what happens if you set the variable "pi" to some value.
Detailed information about the above method can be found here:
Loren on the Art of MATLAB - Constants
<http://blogs.mathworks.com/loren/2006/09/13/constants/>
You can also define a constant that can be initialized once with a value. This value will be kept until CLEAR is executed. See the following example:
myStaticConstant(1)
function y = myStaticConstant(varargin)
persistent varInitialized
if isempty(varInitialized)
if ~isempty(varargin)
varInitialized = varargin{1};
end
end
y = varInitialized;
0 Comments
Sign in to comment.