フィルターのクリア

Integers in Arrays Give Strange Result

3 ビュー (過去 30 日間)
Patrik Forssén
Patrik Forssén 2022 年 11 月 15 日
編集済み: Bruno Luong 2022 年 11 月 15 日
For example, try this,
vec = [pi, -2, uint8(1)]
vec =
1×3 uint8 row vector
3 0 1
vec = [pi, uint16(2), int8(-2)]
vec =
1×3 uint16 row vector
3 2 0
vec = [pi, uint16(2), int16(-2)]
vec =
1×3 uint16 row vector
3 2 0
So, if one element is an integer MATLAB seem to cast every other element in the array to that integer class. If there are several integer elements all elements seem to be cast to the higher integer class and, in a draw, to the unsigned class.
This is an extremely odd behavior. One would expect all elements to be cast to a numeric class that can accurately represent all elements or, at least, all elements cast to 'double' if there are mixed numerical classes in the array.
This can lead to totally wrong results if a user supplies integers to a function, for example this one,
function y = myFun(x, k)
par = [k, -2];
y = par(1) + par(2)*cos(x);
end
myFun(0, 1) will give -1 and myFun(0, uint8(1)) will give the incorrect result 1.
So, is there some logic behind this behavior or is it a bug?

採用された回答

Steven Lord
Steven Lord 2022 年 11 月 15 日
For concatenation see this documentation page. If you concatenate one or more integer arrays with one or more double arrays, the leftmost of the integer arrays will determine the type of the result.
For the behavior of arithmetic see this documentation page.
This is the documented behavior and has been for many years. It is not a bug.
  7 件のコメント
Steven Lord
Steven Lord 2022 年 11 月 15 日
@the cyclist You are correct. The link I posted just covers combining different integer types and doesn't cover combining integer and non-integer data. I thought I remembered it also briefly touching upon integer and non-integer data, but I must have been thinking about the arithmetic page.
Paul
Paul 2022 年 11 月 15 日
Looking at M2 in Bruno's example and the doc page linked by the cyclist, the leftmost integer type governs, not the signedness nor smallest [number of bits] type when concatenating doubles with integer types, IIUC.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by