Why can't the variable "sumt" in my for loop keep on adding numbers?

function out = blur(m,w)
[r,c] = size(m);
out = ones(r,c)*255;
for kk= 1:c
for ll = 1:r
out(kk,ll) = finddims(m,kk,ll,w,r,c);
end
end
end
function ave = finddims(mat,x,y,w,row,col)
sumt = 0;
cou =0;
i1= x-w;
i2 = x+w;
j1 = y-w;
j2 = y+w;
if i1<1
i1 =1;
elseif i2>col
i2 = col;
end
if j1<1
j1 = 1;
elseif j2>row
j2 = row;
end
for mm= i1:i2
for nn = j1:j2
sumt = sumt + mat(nn,mm); % sum doesn't keep on adding in the loop
cou = cou+1;
end
end
ave = uint8(sumt/cou);
end

 채택된 답변

Stephen23
Stephen23 2020년 4월 21일
편집: Stephen23 2020년 4월 21일
"Why can't the variable "sumt" in my for loop keep on adding numbers?"
Because of the class of mat.
Most likely mat has class uint8 (if you are dealing with images), in which case you need to pay attention to what happens when you add a scalar double and a scalar integer:
scalar integer + scalar double => scalar integer
So although sumt starts of being double (i.e. 0), the first time that you do that sum the output is integer, which means sumt is integer, which means that it is limited to 255 (or the maximum for whatever integer class your data has).
The solution is simple: use double to convert the integer before adding:
sumt = sumt + double(mat(nn,mm));
% ^^^^^^^ ^ you need this!

댓글 수: 2

Thank you so much!!! :)
@GrGr: You are welcome! Please remember to accept my answer!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 4월 21일

댓글:

2020년 4월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by