NumPy includes a matrix library numpy.matlib, and functions in this module return a matrix instead of an ndarray object.
An m x n matrix is a rectangular array with m (row) n columns (column) elements.
Elements in a matrix can be numbers, symbols, or mathematical expressions. Here is a matrix of 6 numeric elements with 2 rows and 3 columns:
matlib.empty()
The matlib.empty() function returns a new matrix with the syntax:
numpy.matlib.empty(shape, dtype, order)
Parameter Description:
- shape: Integer or tuple of integers defining the shape of the new matrix
- dtype: optional, data type
- order: C (row first) or F (column first)
import numpy.matlib
import numpy as np
print (np.matlib.empty((2,2)))
# 填充为随机数据
Output result:
[ [-1.49166815e-154 -1.49166815e-154]
[ 2.17371491e-313 2.52720790e-212] ]
numpy.matlib.zeros()
The numpy.matlib.zeros() function creates a zero-padded matrix.
import numpy.matlib
import numpy as np
print (np.matlib.zeros((2,2)))
Output result:
[ [0. 0.]
[0. 0.] ]
numpy.matlib.ones()
The numpy.matlib.ones() function creates a 1-filled matrix.
import numpy.matlib
import numpy as np
print (np.matlib.ones((2,2)))
Output result:
[ [1. 1.]
[1. 1.] ]
numpy.matlib.eye()
The numpy.matlib.eye() function returns a matrix with ones on the diagonal and zeros elsewhere.
numpy.matlib.eye(n, M,k, dtype)
Parameter Description:
- n: Returns the number of rows in the matrix
- M: Returns the number of columns of the matrix, the default is n
- k: the index of the diagonal
- dtype: data type
import numpy.matlib
import numpy as np
print (np.matlib.eye(n = 3, M = 4, k = 0, dtype = float))
Output result:
[ [1. 0. 0. 0.]
[0. 1. 0. 0.]
[0. 0. 1. 0.] ]
numpy.matlib.identity()
The numpy.matlib.identity() function returns an identity matrix of the given size.
The identity matrix is a square matrix, and the elements on the diagonal from the upper left to the lower right (called the main diagonal) are all 1s, and all other elements are 0s.
import numpy.matlib
import numpy as np
# 大小为 5,类型位浮点型
print (np.matlib.identity(5, dtype = float))
Output result:
[ [ 1. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0.]
[ 0. 0. 1. 0. 0.]
[ 0. 0. 0. 1. 0.]
[ 0. 0. 0. 0. 1.] ]
numpy.matlib.rand()
The numpy.matlib.rand() function creates a matrix of a given size with the data randomly padded.
import numpy.matlib
import numpy as np
print (np.matlib.rand(3,3))
Output result:
[ [0.23966718 0.16147628 0.14162 ]
[0.28379085 0.59934741 0.62985825]
[0.99527238 0.11137883 0.41105367] ]
A matrix is always two-dimensional, and an ndarray is an n-dimensional array. Both objects are interchangeable.
import numpy.matlib
import numpy as np
i = np.matrix('1,2;3,4')
print (i)
Output result:
[ [1 2]
[3 4] ]
import numpy.matlib
import numpy as np
j = np.asarray(i)
print (j)
Output result:
[ [1 2]
[3 4] ]
import numpy.matlib
import numpy as np
k = np.asmatrix (j)
print (k)
Output result:
[ [1 2]
[3 4] ]