# Mean Value Along Dim w Mask

Suppose we have a matrix as follows:

``````A=torch.arange(100).view(20,5)
``````

And suppose we also have a mask to apply, such as:

``````B=torch.rand(100).view(20, 5)

``````

Now suppose we also wish to get the mean along Dim=1 but with the mask applied:

`print(torch.mean(A[mask], dim=1))`

But this gives an error, because applying this type of mask causes the matrix to become a vector.

What is the best way to apply a mask and get dim-wise mean values?

Use this -

``````D = torch.where(mask, A, 0).type(torch.float32)
torch.mean(D, dim=1)
``````

Hi Srishti (and J)!

This replaces masked elements with 0.0 that then get mixed in with the
`mean()` computation, diluting it. Based on the pseudocode J posted, I don’t
think this is what he wants.

Computing the mean in terms of a masked sum and a masked count gives
what I think is the desired result:

``````>>> import torch
>>> print (torch.__version__)
1.12.0
>>>
>>> _ = torch.manual_seed (2022)
>>>
>>> A = torch.arange (100).view (20, 5)
>>> B = torch.rand (100).view (20, 5)
>>> mask = B > 0.1
>>>
>>> masked_mean = (mask * A).sum (dim = 1) / mask.sum (dim = 1)
>>>
Note, if an entire row is masked out, the resulting mean will be `nan` which