Nap D. Lover
Nap D. Lover

Reputation: 125

Reshaping an array of matrices into one matrix without a for-loop

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.

Upvotes: 0

Views: 196

Answers (2)

user17112599
user17112599

Reputation:

list comprehension

X = np.r_[[Y[:, :, i].ravel() for i in Y.shape[2]]]

Upvotes: 0

OctoR
OctoR

Reputation: 41

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.

Upvotes: 1

Related Questions