It is necessary to declare the data type each time I change the value?
10 views (last 30 days)
Show older comments
Javier Naranjo
on 12 Dec 2017
Commented: Javier Naranjo
on 12 Dec 2017
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 Comments
Accepted Answer
John D'Errico
on 12 Dec 2017
Edited: John D'Errico
on 12 Dec 2017
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.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!