Appending to pdls generally means you're doing it wrong. You sould at least be able to preallocate if not autothread.
This contains all the information you are looking for (extracting it is an excercise for the reader):
Note: this only solves the 1D case (I assume you're working in 1D bc you flatten with
). In the general case, you need as many dummy dims as you have dims in