简体   繁体   English

总结3D阵列Matlab

[英]Summing 3d array matlab

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. 无论i,j,k的最大值是多少,上面的代码总输出为255。 Please explain 请解释

It prints out 255 because matlab doesn't overflow integers, and the datatype is uint8 它输出255,因为matlab不会溢出整数,并且数据类型为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. 输出将是200和255,因为Matlab将输出钳位在最大值,而不是环绕。 If you use the sum function as given by Dennis, then you get the correct value as Matlab converts to double first 如果您使用Dennis给出的sum函数,则Matlab会先将其转换为double值,然后您将获得正确的值

sum(a)

should give 500 as the output. 应该给500作为输出。

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(:)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM