简体   繁体   中英

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?

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.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM