1.矩阵的初始化
import numpy as np
#(1)创建一个3*5的全0和全1矩阵
myZero = np.zeros([3, 5])
myOnes = np.ones([3, 5])
#(2)生成随机矩阵
myRand = np.random.rand(3, 4)
#(3)单位阵
myEye = np.eye(3) #3*3的单位阵
2.矩阵的元素运算
from numpy import *
#(1)元素相加和相减
myOnes = ones([3, 3])
myEye = eye(3)
print (myOnes + myEye)
print (myOnes - myEye)
#(2)矩阵数乘:一个数乘以一个矩阵
mymatrix = mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
a = 10
print(a * mymatrix)
#(3)矩阵所有元素求和
mymatrix = mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
#(4)矩阵各元素的积:矩阵的点乘同维对应元素的相乘。当矩阵的维度不同时,会根据一定的广播规则将维数
#扩充到一致的形式。
mymatrix1 = mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
mymatrix2 = 1.5 * ones([3, 3])
print(multiply(mymatrix1, mymatrix2))
#(5)矩阵各元素的n次幂:n=5
mylist = mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(power(mylist, 2))
3.矩阵的乘法:矩阵乘矩阵
import numpy as np
tensor1 = np.arrary([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
tensor2 = np.arrary([[1, 2, 3], [1, 2, 3] [1, 2, 3]])
dot_product = tensor1.dot(tensor2)
print(dot_product)
输出结果
[[14, 14, 14],
[32, 32, 32],
[50, 50, 50]]
4.矩阵的转置
from numpy import *
mymatrix = mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print mymatrix.T #转置
mymatrix.transpose() #转置
5.矩阵的其他操作:行列数、切片、复制、比较
from numpy import *
mymatrix = mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[m, n] = shape(mymatrix) #矩阵的行列数
print("矩阵的行数和列数:", m, n)
myscl1 = mymatrix[0] #按行切片
print("按行切片:", myscl1)
myscl2 = mymatrix.T[0] #按列切片
print("按列切片:", myscl2)
mycpmat = mymatrix.copy()
print("复制矩阵:", mycpmat)
#比较
print("矩阵元素的比较:\n", mymatrix < mymatrix.T)
输出结果:
矩阵的行数和列数: 3 3
按行切片: [[1 2 3]]
按列切片: [[1 4 7]]
复制矩阵: [[1 2 3]
[4 5 6]
[7 8 9]]
矩阵元素的比较:
[[False True True]
[False False True]
[False False False]]