Lyndon
Lyndon

Reputation: 55

Mean of non-zero elements in 3d array

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.

Upvotes: 0

Views: 2639

Answers (2)

Dan
Dan

Reputation: 45752

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

Upvotes: 2

tashuhka
tashuhka

Reputation: 5126

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))).';

Upvotes: 1

Related Questions