There might be a way to vectorize the outer loop too, but it's not obvious to me.