點擊這里可以跳轉至
【1】矩陣匯總:http://www.cnblogs.com/HongYi-Liang/p/7287369.html
【2】矩陣生成:http://www.cnblogs.com/HongYi-Liang/p/7275278.html
【3】矩陣加減:現在的位置
【4】矩陣點乘:http://www.cnblogs.com/HongYi-Liang/p/7287324.html
【5】矩陣化簡:http://www.cnblogs.com/HongYi-Liang/p/7464850.html
C++語言:
原理解析:
本節介紹矩陣與矩陣間的加法和減法,兩個行列數相同的矩陣相加,把的矩陣對應的元素分別相加 。兩個行列數相等矩陣相減,把矩陣的對應元素分別相減。
A+B=
矩陣加法:
首先需要判斷矩陣是否行列數相等,在計算中,由於存放矩陣m_vecMatrix我們使用的是二維vector,所以我們需要:
- 判斷合法性
- 把兩個矩陣的第i行元素提取出來
- 把兩個矩陣中此行的第j個元素提取並相加,推入一個臨時向量tempVec中,
- 通過addOneRowToBack()函數將tempVec加入目標向量的m_vecMatrix(矩陣數據區)中
template <typename T> Matrix<T> Matrix<T>::operator+(Matrix<T> &matrix) //運算符重載“+”為矩陣加法 { /*matrix leagality check*/ if(this->m_iRows != matrix.getRows() || this->m_iColumns != matrix.getColumns()) { return *this; } Matrix<T> outputMatrix; vector<T> tempVec; for(int i=0;i<this->m_iRows;i++) { tempVec.clear(); for(int j=0;j<this->m_iColumns;j++) { tempVec.push_back(this->m_vecMatrix[i][j] + matrix.m_vecMatrix[i][j]); } outputMatrix.addOneRowToBack(tempVec); } return outputMatrix; }
矩陣減法:
矩陣減法與加法類似,我們只需要將上述過程賦值一遍,把"+"改為“-”。
template <typename T> Matrix<T> Matrix<T>::operator-(Matrix<T> &matrix) //運算符重載“-”為矩陣減法 { /*matrix leagality check*/ if(this->m_iRows != matrix.getRows() || this->m_iColumns != matrix.getColumns()) { return *this; } Matrix<T> outputMatrix; vector<T> tempVec; for(int i=0;i<this->m_iRows;i++) { tempVec.clear(); for(int j=0;j<this->m_iColumns;j++) { tempVec.push_back(this->m_vecMatrix[i][j] - matrix.m_vecMatrix[i][j]); } outputMatrix.addOneRowToBack(tempVec); } return outputMatrix; }