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
then when you do this:
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.
must work of course, since that just overwrites x. But you can also use this form:
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.
Best Answer