點積運算是參與運算的兩向量各對應位置上元素相乘後,再將各乘積相加。
兩個向量a = [a1, a2,…, an]和b = [b1, b2,…, bn]的點積定義為:
a·b=a1b1+a2b2+……+anbn。
.
使用矩陣乘法,點積還可以寫為:a·b=(a^T )*b
// 這裡的a^T指示矩陣a的轉置。
numpy庫的使用:https://blog.csdn.net/weixin_45627039/article/details/124237992
A = [7,2,3,5,6]
B = [1,5,9,6,3]
方法1(分支語句for 循環計算):
A = [7,2,3,5,6]
B = [1,5,9,6,3]
c = 0
for i in range(len(A)):
c += A[i]*B[i]
print(c) #92
方法2 (dot函數)
import numpy as np
A = np.array([7,2,3,5,6])
B = np.array([1,5,9,6,3])
print(np.dot(A,B)) #92
A = [[1,3],[2,4]]
B = [[4,6],[5,7]]
方法1(分支語句for 循環計算):
A = [[1,3],[2,4]]
B = [[4,6],[5,7]]
c = [[0 for i in range (len(A[0]))]for j in range(len(B))]
for i in range(len(A)):
for j in range(len(A[i])):
for k in range(len(B)):
c[i][j] += A[i][k]*B[k][j]
print(c) #[[19, 27], [28, 40]]
方法2 (dot函數)
import numpy as np
A = [[1,3],[2,4]]
B = [[4,6],[5,7]]
A = np.array(A)
B = np.array(B)
print(np.dot(A,B))
#[[19 27]
#[28 40]]