線性代數-矩陣-加減 C和C++實現

來源:互聯網
上載者:User

標籤:二維   運算   i++   span   vector   pve   etc   賦值   線性   

原理解析:

(此處補圖)

本節編寫矩陣的加法和減法,兩個矩陣相加,即把兩個相同大小的矩陣對應的元素分別相加 。兩個矩陣相減,把兩個相同大小矩陣的對應元素分別相減。

 

C++語言:矩陣加法:

首先需要判斷矩陣是否行列數相等,在計算中,由於存放矩陣m_vecMatrix我們使用的是二維vector,所以我們需要:

  1. 判斷合法性
  2. 把兩個矩陣的第i行元素提取出來
  3. 把兩個矩陣中此行的第j個元素提取並相加,推入一個臨時向量tempVec中,
  4. 通過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;    }
 C語言:

線性代數-矩陣-加減 C和C++實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.