It is necessary to declare the data type each time I change the value?
조회 수: 12 (최근 30일)
이전 댓글 표시
Hello everybody,
I want to declare x as an int8.
For example
x = int8(9);
But if I change to
x= 2;
Then, it changes to double, so I have to do
x = int8(2);
Is there any way to declare x as an int8 in all my script and when I code
x=2
It remains as a int8?
댓글 수: 0
채택된 답변
John D'Errico
2017년 12월 12일
편집: John D'Errico
2017년 12월 12일
MATLAB does not give you the ability to set a variable name as automatically a specific data type. (Unlike old Fortran, where I could tell it that all variables that begin with the letters i through n were of integer type automatically.)
So even though you initially assign
x = int8(9);
then when you do this:
x = 2;
MATLAB sees that 2 is a double precision value, and the assignment "x=" overrides the current datatype of x. So x is now a double.
You have two choices that I can think of.
x = int8(2);
must work of course, since that just overwrites x. But you can also use this form:
x(:) = 2;
x was initially a scalar, of class int8. But the assignment as x(:)= does not overwrite the variable type. It uses the current type of x. As a test try this:
x = int8(9);
whos x
Name Size Bytes Class Attributes
x 1x1 1 int8
x(:) = 2;
whos x
Name Size Bytes Class Attributes
x 1x1 1 int8
x
x =
int8
2
So x remains an int8, without needing to recast x as int8.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!