MATLAB: Calculate the mean of nonzero pixels

digital image processingimageimage analysisimage processingmean

I have a 3D volume and a 3D binary mask. I want to calculate the mean of the pixels which correspond to the regions where the mask is equal to 1.
I thought to calculate the volume with the mask in order to have only the regions I am interested and then I calculated the mean.
I wrote the following piece of code but the mean value is extremely small and I think it's because I am taking into account the whole 3D volume (even the areas where the volume is zero) and not only the regions which I am interested.
r=volume;
for i=1:size(r,1)
for j=1:size(r,2)
for k=1:size(r,3)
masked_volume(i,j,k) = volume(i,j,k)*mask(i,j,k);
end
end
end
mean = mean(masked_volume(:))

Best Answer

The loop was pointless to start with. All you're doing is:
m = mean(volume .* mask, 'all'); %don't use mean as a variable name!
which indeed averages a lot of 0s. The proper way to do this:
m = mean(volume(mask)); %assuming that mask is of type logical