numpy matrix processing

Reprint address: http://blog.sina.com.cn/s/blog_9470b2b00101rt8a.html

Python uses the NumPy package for fast and convenient operations on N-dimensional arrays. To use this package, you need to import numpy. The SciPy package is based on the NumPy package and greatly extends the capabilities of numpy. For the convenience of use, the scipy package includes all numpy content in the outermost namespace, so as long as scipy is imported, there is no need to import numpy separately! But in order to make it clear which are implemented in numpy and which are implemented in scipy, this article makes a distinction. The following are already available by default: import numpy as np and import scipy as sp

The following briefly introduces several differences between Python and MATLAB in dealing with mathematical problems. 1. MATLAB is basically a matrix, while the basic type of numpy is mostly an array, and the matrix is ​​regarded as a subclass of array. 2. MATLAB's index starts from 1, while numpy starts from 0.

1. Create a matrix

a1=np.array([1,2,3],dtype=int) #Create    a one-dimensional array, the data type is int. You can also leave the data type unspecified and use the default. Almost all array creation functions can specify the data type, that is, the value of the dtype.

a2=np.array([[1,2,3],[2,3,4]]) #Create    a two-dimensional array. This is very different from the establishment of a two-dimensional array (matrix) in MATLAB.

Likewise, there are many built-in special matrices in numpy:

b1=np.zeros((2,3)) #Generate     an all-zero matrix with 2 rows and 3 columns. Note that the argument is a tuple: (2,3), so there are two parentheses. The full form is: zeros(shape,dtype=). The same structure, with ones() to build an all-ones matrix. empty() creates an empty matrix and fills the matrix with random values ​​from memory.

b2=identity(n) #Create    an n*n unit matrix, which can only be a square matrix.

b3=eye(N,M=None,k=0)     #Create a matrix whose diagonal is 1 and the rest is 0, and use k to specify the position of the diagonal. M defaults to None.

In addition, numpy also provides several like functions, that is, according to the size of a known array (several rows and columns) to create a special array of the same size. Such functions are zeros_like(), empty_like(), ones_like(), and their parameters are all in the form: zeros_like(a, dtype=), where a is a known array.

c1=np.arange(2,3,0.1) #Start    point, end point, step value. Start value is included, but end value is not included.

c2=np.linspace(1,4,10) #Start     point, end point, number of points in the interval. Start and end points are included. Similarly, there is the logspace() function

d1=np.linalg.companion(a) #Adjoint     matrix

d2=np.linalg.triu()/tril() #The    function is the same as the function of the same name in MATLAB

e1=np.random.rand(3,2) #Generate     a random array with 3 rows and 2 columns. In the same space, there are multiple random functions such as randn()/randint()

fliplr()/flipud()/rot90() #The     function is similar to the MATLAB function .

xx=np.roll(x,2)    #roll() is a cyclic shift function. This call means to rotate 2 bits to the right.

2. Characteristic information of the array

Suppose that there is already an N-dimensional array X, then you can get some attributes of X, these attributes can be input X and a . After that, press the tab key to view the prompt. The object-oriented features of Python are clearly seen here.

X.flags #Array     storage information.

X.shape #The     result is a tuple, returning the number of rows, columns, ...

X.ndim #The    dimension of the array, the result is a number

X.size #Number     of elements in the array

X.itemsize #The     size of the memory space occupied by the data items in the array

X.dtype #Data     type

XT #If    X is a matrix, play the transpose matrix of X

X.trace() #Calculate     the trace of X

np.linalg.det(a) #returns    the determinant of matrix a

np.linalg.norm(a,ord=None) #Calculate     the norm of matrix a

np.linalg.eig(a)    #矩阵a的特征值和特征向量

np.linalg.cond(a,p=None)    #矩阵a的条件数

np.linalg.inv(a)    #矩阵a的逆矩阵

3.矩阵分解

常见的矩阵分解函数,numpy.linalg均已经提供。比如cholesky()/qr()/svd()/lu()/schur()等。某些算法为了方便计算或者针对不同的特殊情况,还给出了多种调用形式,以便得到最佳结果。

4.矩阵运算

np.dot(a,b)用来计算数组的点积;vdot(a,b)专门计算矢量的点积,和dot()的区别在于对complex数据类型的处理不一样;innner(a,b)用来计算内积;outer(a,b)计算外积。

专门处理矩阵的数学函数在numpy的子包linalg中定义。比如 np.linalg.logm(A)计算矩阵A的对数。可见,这个处理和MATLAB是类似的,使用一个m后缀表示是矩阵的运算。在这个空间内可以使用的有cosm()/sinm()/signm()/sqrtm()等。其中常规exp()对应有三种矩阵形式:expm()使用Pade近似算法、 expm2()使用特征值分析算法、expm3()使用泰勒级数算法。在numpy中,也有一个计算矩阵的函数:funm(A,func)。

5.索引

numpy中的数组索引形式和Python是一致的。如:

x=np.arange(10)

print x[2]    #单个元素,从前往后正向索引。注意下标是从0开始的。

print x[-2]    #从后往前索引。最后一个元素的下标是-1

print x[2:5]    #多个元素,左闭右开,默认步长值是1

print x[:-7]    #多个元素,从后向前,制定了结束的位置,使用默认步长值

print x[1:7:2]   #指定步长值

x.shape=(2,5)    #x的shape属性被重新赋值,要求就是元素个数不变。2*5=10

print x[1,3]    #二维数组索引单个元素,第2行第4列的那个元素

print x[0]   #第一行所有的元素

y=np.arange(35).reshape(5,7)    #reshape()函数用于改变数组的维度

print y[1:5:2,::2]    #选择二维数组中的某些符合条件的元素

Guess you like

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