1. 程式人生 > >學習筆記:矩陣的基本運算的實現

學習筆記:矩陣的基本運算的實現

for int size data stdin mat 轉置 span font

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 */

學習筆記:矩陣的基本運算的實現