算法-数学-矩阵

矩阵

        矩阵类:实现矩阵的基本变换

#include <iostream>
#include <cmath>
using namespace std;

const int ROW = 1010;
const int COL = 1010;

class Matrix {
private:
	int n, m;
	int a[ROW][COL];
public:
	Matrix(int row,int col);
	void clear();

	Matrix operator + (const Matrix& rhs)const;
	Matrix operator - (const Matrix& rhs)const;
	Matrix operator * (const Matrix& rhs)const;
};

Matrix::Matrix(int row, int col) :n(row), m(col) {}//默认n,m 小于ROW,COL
void Matrix::clear() {
	n = m = 0;
	//静态数组并没有释放内存
}
Matrix Matrix::operator+(const Matrix& rhs)const {
	if (this->n != rhs.n || this->m != rhs.m)
		throw "Mismatching Matrixs";

	Matrix tmp(rhs.n,rhs.m);
	for (int i(0); i < n; ++i) {
		for (int j(0); j < m; ++j) {
			tmp.a[i][j] = this->a[i][j] + rhs.a[i][j];
		}
	}
	return tmp;
}
Matrix Matrix::operator-(const Matrix& rhs)const {
	if (this->n != rhs.n || this->m != rhs.m)
		throw "Mismatching Matrixs";

	Matrix tmp(rhs.n, rhs.m);
	for (int i(0); i < n; ++i) {
		for (int j(0); j < m; ++j) {
			tmp.a[i][j] = this->a[i][j] - rhs.a[i][j];
		}
	}
	return tmp;
}
Matrix Matrix::operator*(const Matrix& rhs)const {
	if (this->m != rhs.n)
		throw "Mismatching Matrixs";
	Matrix tmp(this->n, rhs.m);
	memset(tmp.a, 0, sizeof(tmp.a));//全部元素赋0

	for (int i(0); i < n; ++i) {
		for (int j(0); j < rhs.m; ++j) {
			for (int k(0); k < m; ++k) {
				tmp.a[i][j] += this->a[i][k] * rhs.a[k][j];
			}
		}
	}
	return tmp;
}

应用:
Gauss消元:求解n元一次方程组。将方程组转换为矩阵形式,再利用三角初等矩阵变换,得到上三角矩阵,最后回代得到解集。

Ax=b。A为系数矩阵,x为解集,b为方程组结果矩阵。

猜你喜欢

转载自blog.csdn.net/qq_31854267/article/details/80175811