Is it possible to create constant variables in MATLAB?

424 views (last 30 days)
I would like to be able to define a variable as a constant, so that after initialization it cannot be changed and attempts to change it result in an error.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 6 Sep 2012
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 % Planck's constant.
h = 6.626068e-34; % Units are m^2 kg / s
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:
% Sample call:
myStaticConstant(1)
function y = myStaticConstant(varargin)
% Keep variable value between function calls.
persistent varInitialized
if isempty(varInitialized) % Value has not been initialized yet.
if ~isempty(varargin) % Input value is not empty.
varInitialized = varargin{1}; % Define value.
end
end
% Return constant value with which the function has been initialized.
y = varInitialized;

More Answers (0)

Categories

Find more on Particle & Nuclear Physics in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!