MATLAB: How to fix weird variable behavior

loopsvariablesweird

I am trying to calculate the running sum of total values for all pixels in an image in order to get the average. The code should be relatively easy:
% Find total and divide by number of pixels totalpixels = 0; runningsum = 0;
for y = 1:image1Y for x = 1:image1X totalpixels= totalpixels+1; % in an incredibly frustrating bit of programming confusion % MATLAB won't allow the value of runningsum to go above 255 temp1 = TestImage1(y, x) temp2 = runningsum runningsum = temp1 + temp2 end end
I started with: runningsum = runningsum + TestImage1(y, x);
No matter what I do, the value of running sum won't go above 255. How do I fix this?
I understand I can use a built-in function. At this point, I want to understand how MATLAB handles variables.

Best Answer

TestImage1(y, x) is a uint8, and so the sum is also. Uint8 varaibels are not allowed to go above 255 and will get clipped if that were to be the case. Try casting to double before summing:
temp1 = double(TestImage1(y, x));