用C++编写一个实现矩阵基础运算(加减乘除,求逆,转置等)的类的完整程序。
时间: 2024-03-16 07:45:54 浏览: 103
以下是一个简单的矩阵类的示例程序,包括基本矩阵运算(加减乘除,求逆,转置等):
```
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
Matrix(int row, int col) : m_row(row), m_col(col) {
m_data.resize(row);
for (int i = 0; i < row; ++i) {
m_data[i].resize(col);
}
}
int row() const { return m_row; }
int col() const { return m_col; }
double& operator()(int i, int j) { return m_data[i][j]; }
double operator()(int i, int j) const { return m_data[i][j]; }
Matrix operator+(const Matrix& other) const {
Matrix res(m_row, m_col);
for (int i = 0; i < m_row; ++i) {
for (int j = 0; j < m_col; ++j) {
res(i, j) = m_data[i][j] + other(i, j);
}
}
return res;
}
Matrix operator-(const Matrix& other) const {
Matrix res(m_row, m_col);
for (int i = 0; i < m_row; ++i) {
for (int j = 0; j < m_col; ++j) {
res(i, j) = m_data[i][j] - other(i, j);
}
}
return res;
}
Matrix operator*(const Matrix& other) const {
Matrix res(m_row, other.m_col);
for (int i = 0; i < m_row; ++i) {
for (int j = 0; j < other.m_col; ++j) {
for (int k = 0; k < m_col; ++k) {
res(i, j) += m_data[i][k] * other(k, j);
}
}
}
return res;
}
Matrix operator/(double scalar) const {
Matrix res(m_row, m_col);
for (int i = 0; i < m_row; ++i) {
for (int j = 0; j < m_col; ++j) {
res(i, j) = m_data[i][j] / scalar;
}
}
return res;
}
Matrix transpose() const {
Matrix res(m_col, m_row);
for (int i = 0; i < m_row; ++i) {
for (int j = 0; j < m_col; ++j) {
res(j, i) = m_data[i][j];
}
}
return res;
}
Matrix inverse() const {
// TODO: implement matrix inverse
return Matrix(m_row, m_col);
}
private:
int m_row;
int m_col;
vector<vector<double>> m_data;
};
int main() {
Matrix A(2, 3);
A(0, 0) = 1; A(0, 1) = 2; A(0, 2) = 3;
A(1, 0) = 4; A(1, 1) = 5; A(1, 2) = 6;
Matrix B(3, 2);
B(0, 0) = 1; B(0, 1) = 2;
B(1, 0) = 3; B(1, 1) = 4;
B(2, 0) = 5; B(2, 1) = 6;
Matrix C = A * B;
Matrix D = C.transpose();
cout << "A:" << endl;
for (int i = 0; i < A.row(); ++i) {
for (int j = 0; j < A.col(); ++j) {
cout << A(i, j) << " ";
}
cout << endl;
}
cout << "B:" << endl;
for (int i = 0; i < B.row(); ++i) {
for (int j = 0; j < B.col(); ++j) {
cout << B(i, j) << " ";
}
cout << endl;
}
cout << "C:" << endl;
for (int i = 0; i < C.row(); ++i) {
for (int j = 0; j < C.col(); ++j) {
cout << C(i, j) << " ";
}
cout << endl;
}
cout << "D:" << endl;
for (int i = 0; i < D.row(); ++i) {
for (int j = 0; j < D.col(); ++j) {
cout << D(i, j) << " ";
}
cout << endl;
}
return 0;
}
```
该程序中定义了一个Matrix类,可以表示一个矩阵。在构造函数中,使用vector实现了矩阵数据的存储,同时提供了访问矩阵元素的操作符()。并且实现了基本的矩阵加、减、乘、除、转置等运算,但是求逆运算需要自行实现。
在main函数中,创建了两个矩阵A和B,并对它们进行了乘法和转置运算,最后输出了它们的值。
阅读全文