index exceeds the number of array elements error

2 ビュー (過去 30 日間)
Ibrahim kaya
Ibrahim kaya 2019 年 8 月 17 日
コメント済み: Ibrahim kaya 2019 年 8 月 17 日
This is my code while i type a as 254 and manually divide it by 32 and use floor(254/32)+1 i get 8 however in the code i gets 9. I dont understand how this can happen, it an esay math computation, could anybody explain it to me?
K=256; %
B=32; % binSize 32 I values are 1 bin;
Hist=zeros(1,2^(log2(K)-log2(B)))
[w, h] =size(I);
for v=1:1:h
for u=1:1:w
a=I(u,v,1);
i=floor(a/B)+1;
Hist(i)=Hist(i)+1
end
end

採用された回答

Walter Roberson
Walter Roberson 2019 年 8 月 17 日
Looking at your code, I speculate that a is datatype uint8()
When you have a/B with a uint8 divided by a double or another uint8 , the result is calculated as if you used
uint8( round(double(a)/double(B)) )
You have the floor(a/B) but that floor() only does something useful if the result of a/B is single() or double() : division with integer data types use round() internally
  3 件のコメント
Walter Roberson
Walter Roberson 2019 年 8 月 17 日
If the number being converted to an integer has a fractional part, MATLAB rounds to the nearest integer.
For all binary operations in which one operand is an array of integer data type (except 64-bit integers) and the other is a scalar double, MATLAB computes the operation using element-wise double-precision arithmetic, and then converts the result back to the original integer data type. For binary operations involving a 64-bit integer array and a scalar double, MATLAB computes the operation as if 80-bit extended-precision arithmetic were used, to prevent loss of precision.
Thus the situation is documented. uint8 divided by double is calculated by converting the uint8 to double, doing the calculation, and converting the result to uint8. Converting double to uint8 rounds. Therefore uint8 divided by double will give the rounded result.
There is no fixed rule in mathematics that dividing one data class by another data class should produce a particular outcome. There are several competing conventions, corresponding to floor(), ceil(), round(), and fix() . For example if you think uint8(254)/32 + 1 should be 8, then what should int16(-254)/32 + 1 be ? Should the truncation you believe should take place be towards negative infinity, -7.9375 -> -8, or should it be towards 0, -7.9375 -> -7 ? What does "simple logic and math" have to say about that?
Ibrahim kaya
Ibrahim kaya 2019 年 8 月 17 日
I think i am not the only person believe that int16(254)/32+1 should be converted to double and -7.9375 + 1 = -6.9375 if it was int16(-254/32+1) the answer should be -7. the problem here is applying the floor and getting the ceil.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by