why float no. become integer?

11 ビュー (過去 30 日間)
huda nawaf
huda nawaf 2012 年 4 月 27 日
hi,
i have two vectors
the first one is float as:
c=[2.5 4 6.5 4.5 3]; c1=[1 2 10 9];
when merge them as:
c2=[c c1]
why c within c2 become [2 4 6 4 3]?
thanks in advance

採用された回答

Walter Roberson
Walter Roberson 2012 年 4 月 27 日
I bet if you check class(c1) you will find it is an integer data type.
  2 件のコメント
huda nawaf
huda nawaf 2012 年 4 月 27 日
yes it is integer
Walter Roberson
Walter Roberson 2012 年 4 月 27 日
Then the answer is "For reasons not explained, combining an integer data type in an array with floating point data is defined by MATLAB to return an integer data type."
If I were to speculate, then I would speculate that it is to allow people to write expressions such as
J = J + 1
when J starts as an integer data type here, it would be surprising for the user for it to suddenly become a floating point data type because the "1" happens to be floating point. It would be a nuisance for the programmer to have to continually write things like
J = J + ones(1, class(J));

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

その他の回答 (2 件)

Image Analyst
Image Analyst 2012 年 4 月 27 日
Because that's how MATLAB does it. If an integer is multiplied by a double, it gives a rounded integer result. Same thing if you combine them like you did. It does not promote the integer variable to the more general double like most languages, and like you would think - I don't know why, that's just the way it is. This was one of the most surprising things I learned when I was learning MATLAB. I can't find the explanation for this in the help - maybe someone else will say where it can be found.
  1 件のコメント
Walter Roberson
Walter Roberson 2012 年 4 月 27 日
When there is a mix of integer and floating point types, the result will be the left-most integer type evaluated in the expression:
>> ([int8([4 5 6]), uint16([1118 1119 11110])])
Warning: Concatenation with dominant (left-most) integer class may overflow other operands on conversion to return class.
ans =
4 5 6 127 127 127

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


Junaid
Junaid 2012 年 4 月 27 日
it might be because of C1, thought in given example it should not do this but if somewhere you have changed c1 to integer then it might be problem. first you type cast the c1
c1 = double(c1);
then
c2 = [c c1];

カテゴリ

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