@Pigmon
2017-04-09T13:30:50.000000Z
字数 1612
阅读 1196
Python
import numpy as np
# array arange(include, exclude, step)np.arange(1, 5) # [1 2 3 4]np.arange(1, 15, 2) # [ 1 3 5 7 9 11 13]np.arange(5) # [0 1 2 3 4]
# 在0到2PI之间均匀的生成50个数字np.linspace(0, 2 * np.pi, 50)
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)arr1 = np.array(tuple1) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# reshape(row, col)# [[ 1 2 3 4 5]# [ 6 7 8 9 10]]arr2 = arr1.reshape(2, 5)# shapearr2.shape; # (2,5)# 各种运算arr2.max() # 10np.max(arr2[1]) # 10np.min(arr2[0]) # 1np.max(arr2[1, :3]) # 8 第二行,前3个数中的最大值np.mean(arr2[0]) # 3.0 第一行平均值np.sum(arr2[1]) # 40,第二行相加np.sum(arr2[:,2]) # 11,第三列相加,即 3 + 8np.sum(arr2, 0) # [ 7 9 11 13 15] 求各列的和np.sum(arr2, 1) # [15 40] 各行的和# [[0 0 0]# [0 0 0]# [0 0 0]]mat_o = np.zeros((3, 3), dtype=np.int32) # 参数2可选,默认float# [[1 0 0]# [0 1 0]# [0 0 1]]mat_i = np.eye(3, dtype=np.int32) # 注意eye只有一个参数,即方阵的阶,如eye(3)代表3阶单位矩阵# [[1 1 1]# [1 1 1]# [1 1 1]]mat_1 = np.ones((3, 3), dtype=np.int32)# typetype(mat_1) # <type 'numpy.ndarray'># sizeprint mat_1.size; # 9# [[1 2 3]# [4 5 6]# [7 8 9]]mat = np.array([1,2,3,4,5,6,7,8,9]).reshape((3,3))print mat[1, 1] # 5,代表第二行第二列,从0开始print mat[0] # [1 2 3]print mat[1] # [4 5 6]print mat[2] # [7 8 9]print mat[:1] # [[1 2 3]]print mat[1:2] # [[4 5 6]]print mat[2:] # [[7 8 9]]print mat[1,:2] # [4 5]# 运算# [[2 1 1]# [1 2 1]# [1 1 2]]print mat_i + mat_1# 矩阵乘法 np.dot(mat1, mat2)# [[ 6 6 6]# [15 15 15]# [24 24 24]]print np.dot(mat, mat_1)# [[1 2 3]# [4 5 6]# [7 8 9]]print np.dot(mat, mat_i)# 逐项乘,即 *# [[1 0 0]# [0 5 0]# [0 0 9]]print mat * mat_i# 逆矩阵# [[ 1. 0. 0.]# [ 0. 1. 0.]# [ 0. 0. 1.]]np.linalg.inv(mat_i)# 转置矩阵# [[1 4 7]# [2 5 8]# [3 6 9]]mat.transpose()
import numpy as npimport sympy as spa,b,c,d,e,f,g,h,i = sp.symbols('a b c d e f g h i')mat = np.array([a,b,c,d,e,f,g,h,i]).reshape((3,3))M = sp.Matrix(mat)print M # Matrix([[a, b, c], [d, e, f], [g, h, i]])print M.det() # a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g
