It is necessary to declare the data type each time I change the value?

7 ビュー (過去 30 日間)
Javier Naranjo
Javier Naranjo 2017 年 12 月 12 日
コメント済み: Javier Naranjo 2017 年 12 月 12 日
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?

採用された回答

John D'Errico
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.
  1 件のコメント
Javier Naranjo
Javier Naranjo 2017 年 12 月 12 日
That worked for me!
Thank you very much!! :)

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by