Instead of pre-allocating the grid and using tricky indexing to fill in the cells, just fully regenerate it. But do it columnwise first, and then transpose it.