# 【筆記】矩陣運算

• 加法、減法：若 為 m×n 矩陣，為 m×n 矩陣，則 A + BA – B 還是一個 m×n 矩陣。
• 乘法：若 為 m×n 矩陣，為 n×p 矩陣，則他們的乘積 AB (或記做A · B)會是一個 m×p 矩陣。
• 【範例】ZeroJudge d481: 矩陣乘法【題解
• 【練習】ZeroJudge a451: 10229 – Modular Fibonacci【題解

#### 【實作】struct

```#include <iostream>
#include <vector>
using namespace std;

struct Matrix{
int row, col;
vector <vector <int> > data;

//constructor
Matrix(int r, int c): row(r), col(c), data(r, vector<int>(c)) {}

Matrix operator + (const Matrix &B) const{
Matrix ret(row, col);
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
ret.data[i][j] = data[i][j] + B.data[i][j];
}
}
return ret;
}

Matrix operator - (const Matrix &B) const{
Matrix ret(row, col);
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
ret.data[i][j] = data[i][j] - B.data[i][j];
}
}
return ret;
}

Matrix operator * (const Matrix &B) const{
Matrix ret(row, B.col);
for (int i = 0; i < row; i++){
for (int j = 0; j < B.col; j++){
for (int k = 0; k < col; k++){
ret.data[i][j] = (ret.data[i][j] + data[i][k] * B.data[k][j]);
}
}
}
return ret;
}
};

void printMatrix (Matrix A){
//print Matrix
for (int i = 0; i < A.row; i++){
for (int j = 0; j < A.col; j++){
cout << A.data[i][j] << " ";
}
cout << "\n";
}
}

int main(){
int a, b, c, d;
cin >> a >> b >> c >> d;

Matrix A(a, b);
Matrix B(c, d);

for (int i = 0; i < a; i++){
for (int j = 0; j < b; j++){
cin >> A.data[i][j];
}
}

for (int i = 0; i < c; i++){
for (int j = 0; j < d; j++){
cin >> B.data[i][j];
}
}

A = A * B;
printMatrix(A);
return 0;
}
```

#### 【實作】class

```#include <iostream>
#include <cstring>
#include <vector>
using namespace std;

class Matrix{
public:
int row, col;
vector <vector <int> > data;

Matrix(int r=0, int c=0): row(r), col(c), data(r, vector<int>(c)) {}

void InputMatrix(){
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cin >> data[i][j];
}

void OutputMatrix(){
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++)
cout << data[i][j] << " ";
cout << "\n";
}
}

Matrix ret(row, col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
ret.data[i][j] = data[i][j] + B.data[i][j];
return ret;
}

Matrix Sub(const Matrix &B){
Matrix ret(row, col);
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
ret.data[i][j] = data[i][j] - B.data[i][j];
return ret;
}

Matrix Mult(const Matrix &B){
Matrix ret(row, B.col);
for (int i = 0; i < row; i++)
for (int j = 0; j < B.col; j++)
for (int k = 0; k < col; k++)
ret.data[i][j] = (ret.data[i][j] + data[i][k] * B.data[k][j]);
return ret;
}
};

int main(){
int a, b, c, d;
cin >> a >> b >> c >> d;
Matrix A(a, b);
Matrix B(c, d);
cout << "\n";
A.InputMatrix();
B.InputMatrix();
cout << "\n";