It is necessary to declare the data type each time I change the value?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Javier Naranjo
am 12 Dez. 2017
Kommentiert: Javier Naranjo
am 12 Dez. 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 Kommentare
Akzeptierte Antwort
John D'Errico
am 12 Dez. 2017
Bearbeitet: John D'Errico
am 12 Dez. 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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!