vectorized code to remove for loops