TheWho
TheWho

Reputation: 939

how to convert list of different shape of arrays to numpy array in Python

I have a different shape of 3D matrices. Such as:

  1. Matrix shape = [5,10,2048]
  2. Matrix shape = [5,6,2048]
  3. Matrix shape = [5,1,2048]

and so on....

I would like to put them into big matrix, but I am normally getting a shape error (since they have different shape) when I am trying to use numpy.asarray(list_of_matrix) function.

What would be your recommendation to handle such a case?

My implementation was like the following:

matrices = []
matrices.append(mat1)
matrices.append(mat2)
matrices.append(mat3)
result_matrix = numpy.asarray(matrices)

and having shape error!!

UPDATE

I am willing to have a result matrix that is 4D.

Thank you.

Upvotes: 2

Views: 2012

Answers (1)

user1245262
user1245262

Reputation: 7505

I'm not entirely certain if this would work for you, but it looks as though your matrices only disagree along the 1st axis, so why not concatenate them:

e.g.

>>> import numpy as np
>>> c=np.zeros((5,10,2048))
>>> d=np.zeros((5,6,2048))
>>> e=np.zeros((5,1,2048))
>>> f=np.concatenate((c,d,e),axis=1)
>>> f.shape
(5, 17, 2048)

Now, you'd have to keep track of which indices of the 1st axis corresponds to which matrices, but maybe this could work for you?

Upvotes: 1

Related Questions