x=imread('test.jpg');
imshow(x);
total = 0;
for i=1:2
for j=1:2
for k=1:2
total = total + abs(x(i,j,k));
end
end
end
total
The above code prints total as 255 no matter what are the max values for i,j,k. Please explain
It prints out 255 because matlab doesn't overflow integers, and the datatype is uint8
a = repmat(uint8(100),5, 1)
a(1)+a(2)
a(1)+a(2)+a(3)
The outputs will be 200 and 255, because Matlab clamps the output at the maximum value, rather than wrapping around. If you use the sum function as given by Dennis, then you get the correct value as Matlab converts to double first
sum(a)
should give 500 as the output.
Not sure what your code fragment is, but if you want to sum of the absolute values of the array it is really easy:
sum(abs(x(:)))
If you just want the submatrix containing the first 2 values from the corner:
subM= x(1:2,1:2,1:2)
sum(abs(subM(:)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.