Tony Tannous
Tony Tannous

Reputation: 14876

Python from matrix to 1-D array

I need to convert B to a 1-D array I have a matrix which I am trying to turn to a 1-D array. However I am getting an array with 1 cell which holds the 1-D array. How do I fix it ?

Python CODE:

import numpy as np


def computecoreset():
    a = np.matrix('1 2 19 22; 3 4 28 11')
    B = a.ravel()
    cal = np.random.choice(B, 3)
    return cal

print(computecoreset())

However:

B = [[ 1  2 19 22  3  4 28 11]]

Which is not the same as

[ 1  2 19 22  3  4 28 11]

Thanks in advance

Upvotes: 0

Views: 846

Answers (2)

gboffi
gboffi

Reputation: 25023

Use np.array to define your 2D arrays.

The extra convenience of specifying data as strings, as in your example, and having a few methods proper to 2D arrays attached to a matrix object are, at least in my opinion, outbalanced by the minor flexibility of the latter data structure, in particular most expressions that involve a matrix lead to a matrix result, even if this is not what you're looking for.

E.g., the double matrix product, i.e., a scalar, when it involves matrix objects is a 2D matrix and you will see the following recurring idiom

x = np.matrix('1;2;3')
K = np.matrix('1 2 3; 2 4 5; 3 5 6')

V = 0.5 * (x.T*K*x)[0,0]

when you want the strain energy of an elastic system represented as free-standing floating point value.

Note also that, using arrays, you have no more to write

V = 0.5*np.dot(x.T, np.dot(K, x))

but you can use the new syntax

V = 0.5 * x.T@K@x

That said, if you still want a matrix, the answer by Divakar is exactly what you want and you're right in accepting it.

Upvotes: 0

Divakar
Divakar

Reputation: 221564

a.ravel() being a method of NumPy matrix would still keep it as a matrix and NumPy matrices can't be 1D. So, instead we can use NumPy's ravel() method to convert into a flattened 1D NumPy array, like so -

np.ravel(a)

Sample run -

In [40]: a
Out[40]: 
matrix([[ 1,  2, 19, 22],
        [ 3,  4, 28, 11]])

In [41]: np.ravel(a)
Out[41]: array([ 1,  2, 19, 22,  3,  4, 28, 11])

Upvotes: 1

Related Questions