c++使用二维数组初始化两个需要进行矩阵乘法运算的不定阶数的矩阵,同时显示可以进行 的矩阵乘法运算方式:a 矩阵的普通乘法,b 矩阵的哈达马积,c 矩阵的克 罗内克积,d 复数矩阵的普通乘法。
时间: 2024-04-30 12:20:39 浏览: 45
以下是一种可能的实现方法:
```c++
#include <iostream>
#include <vector>
#include <complex>
using namespace std;
int main() {
// 初始化矩阵 a 和 b
vector<vector<int>> a = {{1, 2}, {3, 4}};
vector<vector<int>> b = {{5, 6}, {7, 8}};
// 显示矩阵 a 和 b
cout << "Matrix a:" << endl;
for (auto row : a) {
for (auto elem : row) {
cout << elem << " ";
}
cout << endl;
}
cout << "Matrix b:" << endl;
for (auto row : b) {
for (auto elem : row) {
cout << elem << " ";
}
cout << endl;
}
// 普通乘法
if (a[0].size() == b.size()) {
cout << "a * b = " << endl;
vector<vector<int>> c(a.size(), vector<int>(b[0].size()));
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < b[0].size(); j++) {
for (int k = 0; k < b.size(); k++) {
c[i][j] += a[i][k] * b[k][j];
}
cout << c[i][j] << " ";
}
cout << endl;
}
} else {
cout << "a * b not defined" << endl;
}
// 哈达马积
if (a.size() == b.size() && a[0].size() == b[0].size()) {
cout << "a hadamard b = " << endl;
vector<vector<int>> d(a.size(), vector<int>(a[0].size()));
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a[0].size(); j++) {
d[i][j] = a[i][j] * b[i][j];
cout << d[i][j] << " ";
}
cout << endl;
}
} else {
cout << "a hadamard b not defined" << endl;
}
// 克罗内克积
cout << "a kron b = " << endl;
for (int i = 0; i < a.size() * b.size(); i++) {
for (int j = 0; j < a[0].size() * b[0].size(); j++) {
cout << a[i / b.size()][j / b[0].size()] * b[i % b.size()][j % b[0].size()] << " ";
}
cout << endl;
}
// 复数矩阵的普通乘法
vector<vector<complex<int>>> e = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
vector<vector<complex<int>>> f = {{{9, 10}, {11, 12}}, {{13, 14}, {15, 16}}};
if (e[0].size() == f.size()) {
cout << "e * f = " << endl;
vector<vector<complex<int>>> g(e.size(), vector<complex<int>>(f[0].size()));
for (int i = 0; i < e.size(); i++) {
for (int j = 0; j < f[0].size(); j++) {
for (int k = 0; k < f.size(); k++) {
g[i][j] += e[i][k] * f[k][j];
}
cout << g[i][j] << " ";
}
cout << endl;
}
} else {
cout << "e * f not defined" << endl;
}
return 0;
}
```
其中,普通乘法使用三重循环实现;哈达马积和克罗内克积分别使用两重循环实现;复数矩阵的普通乘法同样使用三重循环实现,不过需要使用复数类型 `complex`。在判断矩阵乘法是否可行时,需要注意矩阵的维数是否匹配。
阅读全文