Pippi
Pippi

Reputation: 2571

How can I create a matrix, or convert a 2D array into matrix in Python?

I wish to be able to extract a row or a column from a 2D array in Python such that it preserves the 2D shape and can be used for matrix multiplication. However, I cannot find in the documentation how can this best be done. For example, I can use

a = np.zeros(shape=(6,6)) 

to create an array, but a[:,0] will have the shape of (6,), and I cannot multiply this by a matrix of shape (6,1). Do I need to reshape a row or a column of an array into a matrix for every matrix multiplication, or are there other ways to do matrix multiplication?

Upvotes: 1

Views: 5242

Answers (1)

Akavall
Akavall

Reputation: 86188

You could use np.matrix directly:

>>> a = np.zeros(shape=(6,6)) 
>>> ma = np.matrix(a)
>>> ma
matrix([[ 0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.],
        [ 0.,  0.,  0.,  0.,  0.,  0.]])
>>> ma[0,:]
matrix([[ 0.,  0.,  0.,  0.,  0.,  0.]])

or you could add the dimension with np.newaxis

>>> a[0,:][np.newaxis, :]
array([[ 0.,  0.,  0.,  0.,  0.,  0.]])

Upvotes: 2

Related Questions