matlab 能做的,python 都能做

向量

python中的vector一般由numpy的array结构表示。

自然,向量的运算与array的运算是一样的,但是要区分向量的内积和array间的乘法。

In [1]: import numpy as np

In [2]: x = np.ones(3)            # Vector of three ones

In [3]: y = np.array((2, 4, 6))   # Converts tuple (2, 4, 6) into array

In [4]: x + y
Out[4]: array([ 3.,  5.,  7.])

In [5]: 4 * x
Out[5]: array([ 4.,  4.,  4.])
In [6]: np.sum(x * y)          # 向量内积 Inner product of x and y
Out[6]: 12.0

In [7]: np.sqrt(np.sum(x**2))  # Norm of x, take one
Out[7]: 1.7320508075688772

In [8]: np.linalg.norm(x)      # Norm of x, take two
Out[8]: 1.7320508075688772

矩阵

矩阵就是多维向量组。

In [1]: import numpy as np

In [2]: A = ((1, 2),
   ...:      (3, 4))

In [3]: type(A)
Out[3]: tuple

In [4]: A = np.array(A)

In [5]: type(A)
Out[5]: numpy.ndarray

In [6]: A.shape
Out[6]: (2, 2)
In [8]: A = np.identity(3)

In [9]: B = np.ones((3, 3))

In [10]: 2 * A
Out[10]:
array([[ 2.,  0.,  0.],
       [ 0.,  2.,  0.],
       [ 0.,  0.,  2.]])

In [11]: A + B
Out[11]:
array([[ 2.,  1.,  1.],
       [ 1.,  2.,  1.],
       [ 1.,  1.,  2.]])
<tt class="docutils literal" style="border&#58;1px dotted rgb&#40;204&#44;204&#44;204&#41;&#59;color&#58;rgb&#40;51&#44;51&#44;51&#41;&#59;">矩阵乘法由np.dot(A, B)</tt>   计算,要区别它与A*B的不同。

解线性方程:

在scipy.linalg 中提供的函数的底层代码都是由优化后的Fortran代码组成。

In [9]: import numpy as np

In [10]: from scipy.linalg import inv, solve, det

In [11]: A = ((1, 2), (3, 4))

In [12]: A = np.array(A)

In [13]: y = np.ones((2, 1))  # Column vector

In [14]: det(A)               # 求行列式          Check that A is nonsingular, and hence invertible
Out[14]: -2.0

In [15]: A_inv = inv(A)  #     求逆矩阵              Compute the inverse

In [16]: A_inv
Out[16]:
array([[-2. ,  1. ],
       [ 1.5, -0.5]])

In [17]: x = np.dot(A_inv, y)  #           解方程  Solution

In [18]: np.dot(A, x)  # Should equal y
Out[18]:
array([[ 1.],
       [ 1.]])

In [19]: solve(A, y)  # Produces same solution   解方程 
Out[19]:
array([[-1.],
       [ 1.]])
在scipy中解方程Ax = y 的方法可以是x=np.dot(A_inv,y)也可以是solve(A,y)。

常用的最小二乘解法,数学上为x = (A'*A)_inv*A'*y,scipy中提供了函数scipy.linalg.lstsq(A,y)直接求解。

特征值与特征向量:

In [1]: import numpy as np

In [2]: from scipy.linalg import eig

In [3]: A = ((1, 2),
   ...:      (2, 1))

In [4]: A = np.array(A)

In [5]: evals, evecs = eig(A)

In [6]: evals
Out[6]: array([ 3.+0.j, -1.+0.j])

In [7]: evecs
Out[7]:
array([[ 0.70710678, -0.70710678],
       [ 0.70710678,  0.70710678]])
注意evecs是两个特征向量组成的特征向量组。