Numpy matrix operations

Numpy is a numerical calculation library for Python, which provides many convenient and easy-to-use matrix operation methods. Let's see how to use it.


You need to install this module before using Numpy. It's very simple. The command line executes:

pip install numpy


Import is required before use, generally as follows:

import numpy as np


1. Definition of Matrix

A = np.mat([

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

], dtype=int)


Define the matrix using mat, we define a 3 X 3 matrix here; dtype indicates the data type in the matrix, here is int, the default is floating point number. Here's how some special matrices are defined, taking the creation of a 3 X 3 square matrix as an example:


A matrix with all zero elements:

A = np.mat(np.zeros((3, 3), dtype=int))


A matrix with all 1s:

A = np.mat(np.ones((3, 3), dtype=int))


Unit array:

A = np.mat(np.eye(3, 3, dtype=int))


Diagonal matrix, the diagonal elements are passed as a list:

A = np.diag ([1, 2, 3])


Initialize all elements with a value:

A=np.mat(np.full((3, 3), 12, dtype=int))


2. Matrix operations

Define two matrices A and B as follows:

A = np.mat([

    [1, 2, 3],

    [4, 5, 6],

    [7, 8, 9]

], dtype=int)


B = np.mat([

    [9, 8, 7],

    [6, 5, 4],

    [3, 2, 1]

], dtype=int)


Addition, Subtraction, Multiplication and Transpose:

print(A + B)

print(A - B)

print(A * B)

print(A .T)


The following method is to multiply the elements in sequence, pay attention to distinguish it from matrix multiplication

print (np.multiply (A, B))


Inverse:

C = np.mat([

    [0, 1, 2],

    [1, 0, 3],

    [4, -3, 8]

])

print(C .I)


The example is a non-singular matrix. If the matrix is ​​a singular matrix, a CI exception will be thrown.


3. The determinant of a square matrix

To find the determinant of a square matrix, you can use det

A = np.mat([

    [1, 2, 3],

    [0, 2, 3],

    [1, 2, 0]

])


print (np.linalg.det (A))


4. Rank, eigenvalues ​​and eigenvectors of a matrix

value, vectors = np.linalg.eig(A)

print(value)

print(vectors)


Eigenvalues ​​and eigenvectors can be calculated using eig under numpy's linalg. In the above example, values ​​are eigenvalues ​​and vectors are eigenvectors.


The above are some methods of matrix operations in Numpy, which are very simple and easy to use. I do not give the running results here. With Numpy, we have a powerful numerical calculator.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325580319&siteId=291194637