Is it possible to create constant variables in MATLAB?
71 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
Respuesta aceptada
MathWorks Support Team
el 6 de Sept. de 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 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Performance and Memory en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!