Javascript matrix inversion

天大地大妈咪最大 提交于 2019-12-09 06:09:26

You can also take a look at my (work-in-progress) library matrix.js that supports matrices of any dimension (if you don't need that, you can stop reading here as arbitrary sizes add extreme overhead).

The relevant code for inversion is

Matrix.prototype.inverse = function () {
    if( !this.isSquare() ) {
        throw new MatrixError( MatrixError.ErrorCodes.DIMENSION_MISMATCH, 'Matrix must be square' );
    }

    var M = this.augment( Matrix.eye( this.rows() ) ),
        row, row_before, new_row, i, j, k, factor, rows, columns;

    try {
        M = M.decomposeLU();
        rows = M.rows();
        columns = M.columns();

        for( i = rows; i > 1; i-- ) {
            row_before = M.__getRow( i - 1 );
            row = M.__getRow( i );
            factor = row_before[i - 1] / row[i - 1];

            new_row = [];
            for( k = 0; k < columns; k++ ) {
                new_row[k] = row_before[k] - row[k] * factor;
            }
            M.__setRow( i - 1, new_row );
        }

        for( j = 1; j <= rows; j++ ) {
            row = M.__getRow( j );
            new_row = [];

            for( k = 0; k < columns; k++ ) {
                new_row[k] = row[k] / row[j - 1];
            }

            M.__setRow( j, new_row );
        }
    } catch( e ) {
        throw new MatrixError( MatrixError.ErrorCodes.MATRIX_IS_SINGULAR );
    }

    return M.submatrix( 1, rows, this.columns() + 1, columns );
};

However, you can see it has some dependencies to a LU decomposition, for example. If you're interested, take a look at it. The inverse is not exactly an optimal solution so far, but rather basic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!