20180517函式用於計算矩陣相乘

2021-08-20 02:20:14 字數 1376 閱讀 8609

最近學習python,於是寫下了如下程式:

import numpy as np

def matrixmultip(a, b):

m = a.shape[0]

n = a.shape[1]

n1 = b.shape[0]

h = b.shape[1]

if(n!=n1):

print("the matrix can't multiply!\n")

return 0

else:

c = np.random.rand(m, h)

for i in range(m):

for j in range(h):

c[i][j] = 0

for k in range(n):

c[i][j] += a[i][k]*b[k][j]

return c

測試用例如下:

m = np.random.rand(4, 5)

print(m)

n = np.random.rand(5, 3)

print(n)

c = matrixmultip(m, n)

print(c)

執行結果如下:

[[0.05759342 0.91642957 0.76487463 0.98983764 0.3132928 ]

[0.45148381 0.98424459 0.48097279 0.25893481 0.39565063]

[0.37260015 0.99184222 0.90811488 0.56404501 0.50999819]

[0.42517741 0.75780188 0.92259223 0.97579056 0.71583077]]

[[0.1350007 0.81260325 0.57126273]

[0.13598473 0.70808614 0.46339762]

[0.56981689 0.82154439 0.56143592]

[0.11517964 0.89892064 0.75890407]

[0.52431086 0.15669915 0.62043604]]

[[0.84650603 2.26296833 1.83257031]

[0.70612723 1.75370762 1.42603047]

[1.03499997 2.33809048 1.92679552]

[1.17386643 2.62936837 2.29668665]]

當然還測試了矩陣不匹配的情況,在此就不列出了。

此段程式碼主要是用到了迴圈,而且還考慮了numpy定義陣列的方法。

計算輪廓矩

在這節教程中您將學到 include opencv2 highgui highgui.hpp include opencv2 imgproc imgproc.hpp include include include using namespacecv using namespace std matsr...

正態分佈矩母函式

正態分佈矩母函式的求解 必要公式推導 求的是 exp x 2 2 dx,我們先考慮他的平方 exp x 2 2 dx exp x 2 2 dx exp x 2 2 dx exp y 2 2 dy exp x 2 y 2 2 dxdy 這裡把第二個積分的積分變數從x換成了y,這是可以的 再用極座標變換...

python計算一 二 三階顏色矩

path為需要讀取的路徑 img image.open path m,n img.size r,g,b img.split rd np.asarray r gd np.asarray g bd np.asarray b return rd,gd,bd 分別計算一二三階顏色矩 r通道的一階顏色矩 rd...