Is it possible to create constant variables in MATLAB?
조회 수: 71 (최근 30일)
이전 댓글 표시
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.
채택된 답변
MathWorks Support Team
2012년 9월 6일
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!