c++复数矩阵乘法函数
时间: 2023-10-15 07:05:59 浏览: 144
C++函数矩阵乘法
下面是一个 C++ 复数矩阵乘法的函数示例:
```c++
#include <iostream>
#include <complex>
#include <vector>
using namespace std;
typedef complex<double> Complex;
vector<vector<Complex>> matrix_multiply(vector<vector<Complex>>& A, vector<vector<Complex>>& B) {
int rows_A = A.size();
int cols_A = A[0].size();
int rows_B = B.size();
int cols_B = B[0].size();
if (cols_A != rows_B) {
throw invalid_argument("Matrices are not compatible for multiplication.");
}
vector<vector<Complex>> result(rows_A, vector<Complex>(cols_B));
for (int i = 0; i < rows_A; i++) {
for (int j = 0; j < cols_B; j++) {
result[i][j] = 0;
for (int k = 0; k < cols_A; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
return result;
}
int main() {
vector<vector<Complex>> A = {{1, 2}, {3, 4}};
vector<vector<Complex>> B = {{5, 6}, {7, 8}};
try {
vector<vector<Complex>> C = matrix_multiply(A, B);
for (int i = 0; i < C.size(); i++) {
for (int j = 0; j < C[0].size(); j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
} catch (invalid_argument& e) {
cout << e.what() << endl;
}
return 0;
}
```
该函数使用了 C++ STL 中的 vector 类型来表示矩阵,并使用了复数类型 complex<double>。注意,在计算前,需要判断两个矩阵是否满足相乘的条件(即第一个矩阵的列数等于第二个矩阵的行数)。如果不满足条件,将抛出一个异常。
阅读全文