SoFunction
Updated on 2025-03-01

Detailed explanation of the use of Numpy mat in Python

I have introduced the use of dnarray for simulation, but mat is more in line with the matrix. Here mat is very similar to that in Matlab. (mat is equivalent to matrix)

Basic Operation

>>> m= ([1,2,3]) #Create a matrix>>> m
matrix([[1, 2, 3]])

>>> m[0]        #Take a linematrix([[1, 2, 3]])
>>> m[0,1]       #The first row, the second data2
>>> m[0][1]       #Note that you can't take values ​​like arraysTraceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/lib64/python2.7/site-packages/numpy/matrixlib/", line 305, in __getitem__
  out = .__getitem__(self, index)
IndexError: index 1 is out of bounds for axis 0 with size 1

#Convert Python list to NumPy matrix>>> list=[1,2,3]
>>> mat(list)
matrix([[1, 2, 3]])

#Numpy dnarray conversion to Numpy matrix>>> n = ([1,2,3])
>>> n
array([1, 2, 3])
>>> (n)
matrix([[1, 2, 3]])

#Sort>>> m=([[2,5,1],[4,6,2]])  #Create a matrix of 2 rows and 3 columns>>> m
matrix([[2, 5, 1],
    [4, 6, 2]])
>>> ()          #Sort each row>>> m
matrix([[1, 2, 5],
    [2, 4, 6]])

>>>            #Get the number of rows of the matrix(2, 3)
>>> [0]         #Get the number of rows of the matrix2
>>> [1]         #Get the number of columns of the matrix3

#Index value>>> m[1,:]           #Get all elements of the first linematrix([[2, 4, 6]])
>>> m[1,0:1]          #The first line 0 element, pay attention to the left and right openingmatrix([[2]])
>>> m[1,0:3]
matrix([[2, 4, 6]])
>>> m[1,0:2]
matrix([[2, 4]])

Matrix inversion, determinant

Same as Numpy array, please refer toLink

Matrix multiplication

Matrix multiplication, similar to Numpy dnarray, can use() and(), in addition, since "*" is overloaded in matrix, "*" can also be used for matrix multiplication.

>>> a = ([[1,2,3], [2,3,4]])
>>> b = ([[1,2], [3,4], [5,6]])
>>> a
matrix([[1, 2, 3],
    [2, 3, 4]])
>>> b
matrix([[1, 2],
    [3, 4],
    [5, 6]])
>>> a * b     #Method 1matrix([[22, 28],
    [31, 40]])
>>> (a, b)  #Method 2matrix([[22, 28],
    [31, 40]])
>>> (a, b)   #Method Threematrix([[22, 28],
    [31, 40]])

Click multiply, and only the multiply method is left.

>>> a = ([[1,2], [3,4]])
>>> b = ([[2,2], [3,3]])
>>> (a, b)
matrix([[ 2, 4],
    [ 9, 12]])

Matrix Transposition

There are two ways to transpose:

>>> a
matrix([[1, 2],
    [3, 4]])
>>>       #Method 1, ndarray is OKmatrix([[1, 3],
    [2, 4]])
>>> (a)  #Method 2matrix([[1, 3],
    [2, 4]])

It is worth mentioning that there is another simple method to invert in matrix (not in ndarray):

>>> a
matrix([[1, 2],
    [3, 4]])
>>> 
matrix([[-2. , 1. ],
    [ 1.5, -0.5]])

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.