you should be able to do this in a purely vectorized way avoiding lists and array reallocation.