MATLAB: Reshaping a complex 3D array into 1D, and back

arrayreshape

I have a 3D complex array of size (nx,ny,nz).
For post-processing purposes I need to convert into a flattened array of size (1,nx*ny*nz)
I then need to convert it back into its 3D form.
The issue here is that the following code destroys the original formatting of the 3D array
1dwave = reshape(3dwave,[nx*ny*nz,1]);
recovered_wave = reshape(1dwave,size(3dwave));
In essence:
1dwave != recovered_wave
Can somebody tell me what the correct way to do this is?
i.e. How can I convert from 3D -> 1D -> 3D whilst preserving shape of the original 3D array

Best Answer

I suspect the problem may be that you originally put the data into rows of a matrix. This separates the elements in memory. I.e., MATLAB is column ordered for memory layout, and elements of the same column are next to each other in memory. Elements of the same row are not next to each other in memory in general. Once you put the data into rows you have changed the memory layout of the data, and no amount of reshaping will recover the original memory layout of the data. You would have to probably use the permute( ) function to get back to your desired memory layout.