MATLAB Answers

Is it possible to create constant variables in MATLAB?

1,133 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;

  0 Comments

Sign in to comment.

More Answers (1)

Mohamed Elewoday
Mohamed Elewoday on 21 Dec 2020
How to use Matlab to find a Taylor series of the multi-variable function , where are constans?

  1 Comment

Walter Roberson
Walter Roberson on 7 Feb 2021 at 9:46
syms a b x y x0 y0
f = 1/(1 - a*x + b * y)
f = 
ORDER = 6
ORDER = 6
T = simplify(taylor(taylor(f, x, x0, 'Order', ORDER), y, y0, 'Order', ORDER))
T = 

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!