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

Question:

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?

Asked By: johnny rotten

||

Answers:

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.

Answered By: yagod
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.