C++: Matrix elementary row transformation, into the simplest matrix

The simplest matrix is ​​divided into the following steps

Simplify from row i=0 of the matrix

1. Find the longest element row: starting from the i-th row, look for the first row whose element is not 0 at the beginning, and use row swap to change the row to the i-th row of the matrix.

2. Simplify the i-th row: all the elements in the i-th row are the same except the first non-zero element of the row.

3. Matrix row simplification: Start from the j=0th row of the matrix. The element in the same column as the first non-zero element in the i-th row is the multiple of the row simplification. Each row subtracts this multiple * the value of the i-th row to get the result of a row simplification. Go back to step 1, i++.

 

/**
 * 矩阵行变换成最简矩阵
 * @tparam ElemType
 * @return
 */
template<typename ElemType>
SmartDongLib::Matrix<ElemType> SmartDongLib::Matrix<ElemType>::simplyTransform() {
    Matrix<ElemType> ret(*this);
    //表示将要化1的矩阵行
    for (int transferRow = 0; transferRow < theRows_; ++transferRow) {
        //按列循环每行找首个非0元素,从transferRow行开始寻找最长元素行
        int firstNotNullCol = 0;
        for (; firstNotNullCol < ret.theCols_; ++firstNotNullCol) {
            int row = transferRow;
            bool isfind= false;
            for (; row < ret.theRows_; ++row) {
                ElemType firstelem=ret(row, firstNotNullCol);
                if (!close(firstelem, (ElemType)0 )) {
                    isfind = true;
                    break;
                }
            }
            if (isfind){
                //如果找到最长元素行,则和transferRow行进行行交换
                ret.rowSwap(transferRow,row);
                break;
            }
        }
        if (firstNotNullCol >= ret.theCols_){
            //零矩阵或者后继行都是0
            return ret;
        }
        //当前行首元素化1
        Real factor = ret(transferRow,firstNotNullCol);
        for (int col = firstNotNullCol; col < ret.theCols_; ++col) {

            ret(transferRow,col) =  ret(transferRow,col) / factor;

        }
        //同列元素行化0
        for (int i = 0 ; i <  ret.theRows_; ++i) {
            if ( i ==transferRow )
                continue;
            Real factor2 = ret(i,firstNotNullCol);
            for (int j = firstNotNullCol; j <  ret.theCols_; ++j) {
                ret(i,j) = ret(i,j) -  ret(transferRow,j) * factor2;
            }
        }
    }
    return ret;
}

Note: This code has operator overloading on parentheses and only provides programming ideas. If you have suggestions for code optimization, you can comment.

Guess you like

Origin blog.csdn.net/superSmart_Dong/article/details/111026341