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

111 views (last 30 days)
Nick Keepfer
Nick Keepfer on 18 Jun 2020
Answered: James Tursa on 18 Jun 2020
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
Nick Keepfer
Nick Keepfer on 18 Jun 2020
That was my suspicion, I was expecting it to work too.
So I have simplified my entire process somewhat, to aid with the understanding of the problem, but let me elaborate.
I have T samples of a 3D (nx,ny,nz) array. I then (each loop iteration) save the flattened version of the 3D array into a row of a matrix
u(T,:) = 1dwave;
Once the loop completes, If I pull out say u(T,1) and attempt to reshape it as specified above, it does not match the input. With no doubt, the original size is strictly 3D with dimensions nx, ny, nz.
Perhaps the act of stacking these samples inside "u" causes some problems in how Matlab reformulates the array.

Sign in to comment.

Accepted Answer

James Tursa
James Tursa on 18 Jun 2020
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.

More Answers (1)

David Hill
David Hill on 18 Jun 2020
  1 Comment
Nick Keepfer
Nick Keepfer on 18 Jun 2020
Unfortunately this doesn't work either. Please look at my comment above though which elaborates further

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by