# 重新實現矩陣乘法，可用來實現其他詭異的類似於矩陣乘法的操作

$$A$$$$m*n$$矩陣
$$B$$$$n*p$$矩陣

$$a = A_{i,*}$$$$b = B_{*,j}$$，易知$$a$$$$b$$皆爲$$n$$維向量，則
$$C_{i,j} = a · b = \sum_k^n{a_k * b_k}$$
-----上面都是矩陣乘法的廢話（？

import numpy as np

def matrix_mul(A, B):
m, n = A.shape
n, p = B.shape
# 擴展A和B以匹配維度
A_expanded = np.repeat(A[:, :, np.newaxis], p, axis=2)
B_expanded = np.repeat(B[np.newaxis, :, :], m, axis=0)
# 計算元素乘積
mul = A_expanded * B_expanded
# 計算和
D = np.sum(mul, axis=1)
return D

# 生成示例矩陣
A = np.random.randint(0, 5, (3, 4))
B = np.random.randint(0, 5, (4, 5))
# 運行運算
D = matrix_mul(A, B)
print(A)
print(B)
print(D)
E = np.matmul(A, B)
print(E)
# 輸出0表示矩陣D和E完全相同
print(np.sum(D != E))


import numpy as np

def matrix_avg_diff(A, B):
m, n = A.shape
n, p = B.shape
# 擴展A和B以匹配維度
A_expanded = np.repeat(A[:, :, np.newaxis], p, axis=2)
B_expanded = np.repeat(B[np.newaxis, :, :], m, axis=0)
# 計算絕對差值
diff = np.abs(A_expanded - B_expanded)
# 計算平均值
D = np.mean(diff, axis=1)
return D

# 生成示例矩陣
A = np.random.randint(0, 5, (3, 4))
B = np.random.randint(0, 5, (4, 5))
# 運行運算
D = matrix_avg_diff(A, B)
print(A)
print(B)
print(D)