Here is a vectorized solution using NumPy to compute a running sum over a batch of vectors, with the sum resetting whenever a zero appears in the vector:
python
import numpy as np
def running_sum_with_zero_reset(batch):
"""
Compute the running sum of a batch of vectors, with the sum resetting whenever a zero appears in the vector.
Parameters:
batch (numpy.ndarray): A 2D NumPy array of shape (M, N), where M is the number of vectors and N is the length of each vector.
Returns:
numpy.ndarray: A 2D NumPy array of shape (M, N), where the i-th row contains the running sum of the i-th vector, with the sum resetting whenever a zero appears in the vector.
"""
# Create an array of zeros with the same shape as the input batch
running_sum = np.zeros_like(batch)
# Compute the cumulative sum along the columns of the input batch
cumsum = np.cumsum(batch, axis=1)
# Create a boolean mask indicating where the cumulative sum is zero
zero_mask = np.where(cumsum == 0, True, False)
# Propagate the zero mask backwards along the rows of the cumulative sum
zero_mask = np.logical_or.reduce(np.fliplr([zero_mask] * batch.shape[0]), axis=0)
# Compute the running sum using the cumulative sum and the zero mask
running_sum = np.where(zero_mask, 0, cumsum)
return running_sum
In this example, the running sum of the first vector is [1, 3, 6, 0, 5, 0, 7], where the sum resets to zero whenever a zero appears in the vector. The running sum of the second vector is [4, 0, 9, 0, 1, 3, 0], where the sum resets to zero after the second element because the third element is zero.