Vectorized cost function