I am looking for a fast way to calculate the mean for each row of a 2d matrix but only until a specific column. The remaining values of each row can be ignored. The column is different for each row.
In Numpy, it could be coded like this. However, I am hoping to find a solution without a for loop which also does not break the gradients.
import numpy as np
arr = np.linspace(0, 10, 15).reshape(3,5)
cols = [2,0,4]
for row, col in enumerate(cols):
arr[row, col+1:] = np.nan
result = np.nanmean(arr, axis=1)
Any suggestions?
Edit: Best solution I have found so far:
result = torch.stack([arr[i, 0:cols[i]+1].mean() for i in range(len(arr))])
But I would still like to avoid the for loop.