Mean of non-zero elements in 3d array

半腔热情 提交于 2021-01-29 11:34:41

问题


I have this i x j x k 3d matrix (it's a movie). Without loops, I'm trying to take the mean of the non-zero positive elements in each ixj array and put these values into a 1x1xk matrix.

I've been searching for quite a while now, and although there's plenty of solutions to accomplish this for a 2d matrix, I can't for the life of me find a way to do it for a 3d matrix without using a loop.


回答1:


What if you convert each image (frame) into an array:

% Remove negative and zero elements
A(A<=0) = 0;
% Convert each image into array
B = reshape(A,[Nimg,Nfrm]);
% Extract mean value of each image
C = mean(B,1);

where Nimg is the number of pixels in each image and Nfrm is the number of images.

If you don't want to include the non-zero and negative numbers in the mean denominator (as @Dan suggests), just scale the result with the following line:

C_Dan = C.*squeeze(Nimg./sum(sum(A>0))).';



回答2:


If you want no loops then how about just dividing the sum of each frame by the number of nonzero elements:

sum(sum(A))./sum(sum(A ~= 0))

To get rid of negative numbers, first run A(A < 0) = 0 as pointed out by tashuhka



来源:https://stackoverflow.com/questions/17989403/mean-of-non-zero-elements-in-3d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!