@Pigmon
2017-04-09T21:30:50.000000Z
字数 1612
阅读 911
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)
# shape
arr2.shape; # (2,5)
# 各种运算
arr2.max() # 10
np.max(arr2[1]) # 10
np.min(arr2[0]) # 1
np.max(arr2[1, :3]) # 8 第二行,前3个数中的最大值
np.mean(arr2[0]) # 3.0 第一行平均值
np.sum(arr2[1]) # 40,第二行相加
np.sum(arr2[:,2]) # 11,第三列相加,即 3 + 8
np.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)
# type
type(mat_1) # <type 'numpy.ndarray'>
# size
print 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 np
import sympy as sp
a,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