矩阵运算代码c++
时间: 2023-06-22 10:30:09 浏览: 150
C++矩阵运算代码
4星 · 用户满意度95%
以下是 C++ 中实现矩阵运算的基本代码:
```
#include <iostream>
#include <vector>
using namespace std;
// 定义矩阵数据类型
typedef vector<vector<double>> Matrix;
// 矩阵加法
Matrix matrixAddition(Matrix A, Matrix B) {
int m = A.size(), n = A[0].size();
Matrix C(m, vector<double>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
return C;
}
// 矩阵乘法
Matrix matrixMultiplication(Matrix A, Matrix B) {
int m = A.size(), n = A[0].size(), l = B[0].size();
Matrix C(m, vector<double>(l));
for (int i = 0; i < m; i++) {
for (int j = 0; j < l; j++) {
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
int main() {
// 定义两个矩阵
Matrix A = {{1, 2}, {3, 4}};
Matrix B = {{5, 6}, {7, 8}};
// 矩阵加法
Matrix C = matrixAddition(A, B);
cout << "Matrix addition result:" << endl;
for (auto row : C) {
for (auto elem : row) {
cout << elem << " ";
}
cout << endl;
}
// 矩阵乘法
Matrix D = matrixMultiplication(A, B);
cout << "Matrix multiplication result:" << endl;
for (auto row : D) {
for (auto elem : row) {
cout << elem << " ";
}
cout << endl;
}
return 0;
}
```
以上代码实现了矩阵加法和矩阵乘法操作,并在主函数中进行了示例操作。可以根据自己的需求进行修改和扩展。
阅读全文