How do I fix weird variable behavior?
2 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Image Analyst
on 5 Jul 2014
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));
2 Comments
Image Analyst
on 5 Jul 2014
If it works, could you mark the answer as "Accepted" so I get credit for it? Thanks.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!