如何用C++实现n个矩阵相乘
时间: 2024-03-17 20:44:23 浏览: 64
c++实现矩阵相乘
5星 · 资源好评率100%
实现n个矩阵的相乘可以采用递归的方式,将矩阵分为两个部分,左边的部分递归相乘,右边的部分递归相乘,然后再将两个结果矩阵相乘,最终得到n个矩阵的乘积。
下面是一个示例代码,假设有三个矩阵A、B、C,要计算它们的乘积ABC:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义矩阵类
class Matrix {
public:
Matrix(int r, int c) : rows(r), cols(c), data(r, vector<int>(c)) {}
// 矩阵乘法
Matrix operator*(const Matrix& other) const {
Matrix res(rows, other.cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < other.cols; j++) {
int sum = 0;
for (int k = 0; k < cols; k++) {
sum += data[i][k] * other.data[k][j];
}
res.data[i][j] = sum;
}
}
return res;
}
// 矩阵拆分
pair<Matrix, Matrix> split() const {
int mid = rows / 2;
Matrix A(mid, cols), B(rows - mid, cols);
for (int i = 0; i < mid; i++) {
for (int j = 0; j < cols; j++) {
A.data[i][j] = data[i][j];
}
}
for (int i = mid; i < rows; i++) {
for (int j = 0; j < cols; j++) {
B.data[i - mid][j] = data[i][j];
}
}
return make_pair(A, B);
}
private:
int rows, cols;
vector<vector<int>> data;
};
// 矩阵相乘函数
Matrix multiply(const vector<Matrix>& matrices, int start, int end) {
if (start == end) {
return matrices[start];
} else if (end - start == 1) {
return matrices[start] * matrices[end];
} else {
int mid = (start + end) / 2;
Matrix A = multiply(matrices, start, mid);
Matrix B = multiply(matrices, mid + 1, end);
return A * B;
}
}
int main() {
// 定义矩阵A、B、C
Matrix A(2, 3);
A.data = {{1, 2, 3}, {4, 5, 6}};
Matrix B(3, 2);
B.data = {{7, 8}, {9, 10}, {11, 12}};
Matrix C(2, 2);
C.data = {{13, 14}, {15, 16}};
// 计算ABC
vector<Matrix> matrices = {A, B, C};
Matrix ABC = multiply(matrices, 0, matrices.size() - 1);
// 输出结果
for (int i = 0; i < ABC.rows; i++) {
for (int j = 0; j < ABC.cols; j++) {
cout << ABC.data[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果为:
```
732 804
1686 1854
```
阅读全文