2017-09-05 21:33:33
writer:pprp
昨天开始就上课了,没有整天整天的时间去编代码了,充分抓住每天晚上的时间吧,
今天下午预习了一下线性代数中矩阵最基本的运算,今晚就打算实现一下基本的功能
矩阵加法,矩阵减法,矩阵乘法,矩阵转置
代码如下:
/* @theme:矩阵类的实现 @writer:pprp @begin:20:48 @end:21:30 @declare:注意行还有列的赋值 @date:2017/9/5 */ #include <bits/stdc++.h> using namespace std; #define N 100 int MAXN, n, mod; class Matrix { public: int data[N][N]; int col, row; void Init() { memset(data,0,sizeof(data)); } //test:ok void MatrixMultiply(const Matrix& A, const Matrix & B) { if(A.col != B.row) { cout << "A.col != B.row" << endl; return ; } Init(); row = A.row, col = B.col; //更新乘法得到的矩阵的行和列 for(int i = 0 ; i < A.row ; i++) { for(int j = 0 ; j < B.col; j++) { data[i][j] = 0; for(int k = 0 ; k < A.col; k++) { data[i][j] += A.data[i][k] * B.data[k][j]; } } } } //test:ok void MatrixAdd(const Matrix & A,const Matrix & B) { if(A.row != B.row || A.col != B.col) { cout << "can‘t add these two Matrix!" << endl; return ; } Init(); row = B.row, col = B.col; for(int i = 0 ; i < row; i++) { for(int j = 0; j < col; j++) { data[i][j] = A.data[i][j] + B.data[i][j]; } } } //test:ok void MatrixSub(const Matrix & A, const Matrix & B) { if(A.row != B.row || A.col != B.row) { cout << "can‘t sub the two Matrix!" << endl; return; } row = B.row, col = A.col; for(int i = 0 ; i < row; i++) { for(int j = 0 ; j < col; j++) { data[i][j] = A.data[i][j] - B.data[i][j]; } } } //test:ok void MatrixReverse(const Matrix & A) { row = A.col, col = A.row; Init(); for(int i = 0 ; i < row; i++) { for(int j = 0 ; j < col; j++) { data[i][j] = A.data[j][i]; } } } //test:ok void OutputMatrix()const { for(int i = 0 ; i < row; i++) { for(int j = 0 ; j < col; j++) { cout << data[i][j] << " "; } cout << endl; } } //test:ok void SetRC(int r,int c) { row = r, col = c; } //test:ok void InputMatrix() { Init(); for(int i = 0 ; i < row; i++) { for(int j = 0; j < col; j++) { cin >> data[i][j]; } } } }; int main() { freopen("in.txt","r",stdin); Matrix mx1, mx2, ans; //第一个矩阵 cout << "input the row and the col of the first Matrix" << endl; int row, col; cin >> row >> col; mx1.SetRC(row,col); cout << "input the first Matrix" << endl; mx1.InputMatrix(); mx1.OutputMatrix(); //第二个矩阵 cout << "input the row and the col of the second Matrix" << endl; cin >> row >> col; mx2.SetRC(row,col); cout << "input the second Matrix" << endl; mx2.InputMatrix(); mx2.OutputMatrix(); /* cout << "add:" << endl; ans.MatrixAdd(mx1,mx2); ans.OutputMatrix(); cout << "sub:" << endl; ans.MatrixSub(mx1,mx2); ans.OutputMatrix(); cout << "reverse:" << endl; ans.MatrixReverse(mx2); ans.OutputMatrix(); */ cout << "multiply: " << endl; ans.MatrixMultiply(mx1,mx2); ans.OutputMatrix(); return 0; } /* test: 2 3 1 2 3 4 5 6 3 3 1 -1 2 0 1 1 -1 1 -1 */
时间: 2024-11-13 12:18:05