Home > Mobile >  Turning a vector of length n squared into a matrix of size n times n python
Turning a vector of length n squared into a matrix of size n times n python

Time:11-30

In python I have a numpy vector array v of length n squared. I want to make it into a matrix M of size n times n, by laying the elements of n into n rows, so the first n elements of v comprise the first row of M, similarly the i-th n elements of v comprise the i-th row of M.

I tired using numpy reshape, but as I am completely new to python I couldn't figure out how this is done. How can the above be done?

CodePudding user response:

You're definitely on the right track, you want to use np.reshape() here by doing

M = M.reshape(n,n)

or

M = np.reshape(M, (n,n))

Note the extra parentheses in the second case, they are important for it to work right because you are passing the tuple (n,n) as an argument.

  • Related