I want to reshape an array of matrices into a single matrix, so that if the original array has shape (n, m, N) the new matrix, X, has shape (N, nxm) and in a way so that if we look at X[i,:].reshape(n,m) we would get back the original i-th matrix.
This can be done with a for-loop and ravel:
X = np.zeros((N, n*m))
for i in range(N):
X[i, :]=Y[:,:,i].ravel() # Y is the original array with shape (n,m,N)
print(X.shape)
Question
Is there a way to do this without using a for-loop, perhaps with just reshape and some other functions? I did not quite find this case when I tried to search online, and doing simply X=Y.reshape((N, n*m)) does not preserve the matrix structure when we check an entry as described above.
CodePudding user response:
Before np.reshape, you can use np.moveaxis (e.g. np.moveaixs(Y, -1, 0)) to move the last axis of Y to the first and make its size to (N, n, m) with the matrix stucture preserved.
CodePudding user response:
list comprehension
X = np.r_[[Y[:, :, i].ravel() for i in Y.shape[2]]]
