Is there any way to vectorize this double loop...