index exceeds the number of array elements error

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일

0 개 추천

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

Ibrahim kaya's comment:
Thank you for the explanation, however this is very disturbing. It is against simple logic and math.
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?
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개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

릴리스

R2018b

질문:

2019년 8월 17일

댓글:

2019년 8월 17일

Community Treasure Hunt

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

Start Hunting!

Translated by