Numpy matrix to array

Posted on

Question :

Numpy matrix to array

I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements.

For example, if i have M = matrix([[1], [2], [3], [4]]), I want to get A = array([1,2,3,4]).

To achieve it, I use A = np.array(M.T)[0]. Does anyone know a more elegant way to get the same result?

Thanks!

Asked By: yassin

||

Answer #1:

If you’d like something a bit more readable, you can do this:

A = np.squeeze(np.asarray(M))

Equivalently, you could also do: A = np.asarray(M).reshape(-1), but that’s a bit less easy to read.

Answered By: Joe Kington

Answer #2:

result = M.A1

https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.matrix.A1.html

matrix.A1
1-d base array
Answered By: hpaulj

Answer #3:

A, = np.array(M.T)

depends what you mean by elegance i suppose but thats what i would do

Answered By: mvu

Answer #4:

You can try the following variant:

result=np.array(M).flatten()
Answered By: bubble

Answer #5:

np.array(M).ravel()

If you care for speed; But if you care for memory:

np.asarray(M).ravel()
Answered By: Kevad

Answer #6:

Or you could try to avoid some temps with

A = M.view(np.ndarray)
A.shape = -1
Answered By: Pierre GM

Answer #7:

First, Mv = numpy.asarray(M.T), which gives you a 4×1 but 2D array.

Then, perform A = Mv[0,:], which gives you what you want. You could put them together, as numpy.asarray(M.T)[0,:].

Answered By: oracleyue

Answer #8:

This will convert the matrix into array

A = np.ravel(M).T
Answered By: Siraj S.

Leave a Reply

Your email address will not be published.