Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

อัลกอริทึมการคูณเมทริกซ์ (Matrix Multiplication)


เงื่อนไขการคูณ

เมทริกซ์ A (m×n) และ B (p×q) คูณได้ก็ต่อเมื่อ n = p ผลลัพธ์ C จะเป็น (m×q)

อัลกอริทึม

matrixMultiply(A, B):
  if n != p: exit
  define C(m, q)
  for i = 0 to m-1:
    for j = 0 to q-1:
      for k = 0 to p-1:
        C[i][j] += A[i][k] * B[k][j]

ตัวอย่าง C++

#include <iostream>
using namespace std;

int main() {
    int product[10][10], r1=3, c1=3, r2=3, c2=3;
    int a[3][3] = {{2,4,1},{2,3,9},{3,1,8}};
    int b[3][3] = {{1,2,3},{3,6,1},{2,4,7}};
    // Check dimensions, print matrices, multiply, print result
    // ... (ดูโค้ดเต็มในต้นฉบับ)
}

Output

The first matrix is:
2 4 1
2 3 9
3 1 8

The second matrix is:
1 2 3
3 6 1
2 4 7

Product of the two matrices is:
16 32 17
29 58 72
22 44 66