Simple 3x3 matrix inverse code (C++)

后端 未结 13 2071
花落未央
花落未央 2020-12-04 19:35

What\'s the easiest way to compute a 3x3 matrix inverse?

I\'m just looking for a short code snippet that\'ll do the trick for non-singular matrices, possibly using C

13条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 20:04

    I have just created a QMatrix class. It uses the built in vector > container. QMatrix.h It uses the Jordan-Gauss method to compute the inverse of a square matrix.

    You can use it as follows:

    #include "QMatrix.h"
    #include 
    
    int main(){
    QMatrix A(3,3,true);
    QMatrix Result = A.inverse()*A; //should give the idendity matrix
    
    std::cout<

    The inverse function is implemented as follows:

    Given a class with the following fields:

    template class QMatrix{
    public:
    int rows, cols;
    std::vector > A;
    

    the inverse() function:

    template 
    QMatrix QMatrix:: inverse(){
    Identity Id(rows); //the Identity Matrix as a subclass of QMatrix.
    QMatrix Result = *this; // making a copy and transforming it to the Identity matrix
    T epsilon = 0.000001;
    for(int i=0;i0;--i){
        for(int j=i-1;j>=0;--j){
            T temp = Result(j,i);
            Id(j) = Id(j) - temp*Id(i);
            Result(j)=Result(j)-temp*Result(i);
        }
    }
    
    return Id;
    }
    

提交回复
热议问题