矩陣求逆
阿新 • • 發佈:2019-01-15
fort complex The 也有 com func fortran 驗證 驗證過
// 轉載自: http://fortranwiki.org/fortran/show/Matrix+inversion
// 這裏僅適用於 小型矩陣 2*2,3*3,4*4 的矩陣求逆。事實上,對於這種規模的矩陣,直接寫出求逆的結果速度更快。
// 這裏3*3 的矩陣我已經驗證過了,其余的未驗證。一般矩陣的求逆方法原鏈接中也有。
pure function matinv2(A) result(B) !! Performs a direct calculation of the inverse of a 2×2 matrix. complex(wp), intent(in) :: A(2,2) !! Matrix complex(wp) :: B(2,2) !! Inverse matrix complex(wp) :: detinv ! Calculate the inverse determinant of the matrix detinv = 1/(A(1,1)*A(2,2) - A(1,2)*A(2,1)) ! Calculate the inverse of the matrix B(1,1) = +detinv * A(2,2) B(2,1) = -detinv * A(2,1) B(1,2) = -detinv * A(1,2) B(2,2) = +detinv * A(1,1) end function pure function matinv3(A) result(B) !! Performs a direct calculation of the inverse of a 3×3 matrix. complex(wp), intent(in) :: A(3,3) !! Matrix complex(wp) :: B(3,3) !! Inverse matrix complex(wp) :: detinv ! Calculate the inverse determinant of the matrix detinv= 1/(A(1,1)*A(2,2)*A(3,3) - A(1,1)*A(2,3)*A(3,2)& - A(1,2)*A(2,1)*A(3,3) + A(1,2)*A(2,3)*A(3,1)& + A(1,3)*A(2,1)*A(3,2) - A(1,3)*A(2,2)*A(3,1)) ! Calculate the inverse of the matrix B(1,1) = +detinv * (A(2,2)*A(3,3) - A(2,3)*A(3,2)) B(2,1) = -detinv * (A(2,1)*A(3,3) - A(2,3)*A(3,1)) B(3,1) = +detinv * (A(2,1)*A(3,2) - A(2,2)*A(3,1)) B(1,2) = -detinv * (A(1,2)*A(3,3) - A(1,3)*A(3,2)) B(2,2) = +detinv * (A(1,1)*A(3,3) - A(1,3)*A(3,1)) B(3,2) = -detinv * (A(1,1)*A(3,2) - A(1,2)*A(3,1)) B(1,3) = +detinv * (A(1,2)*A(2,3) - A(1,3)*A(2,2)) B(2,3) = -detinv * (A(1,1)*A(2,3) - A(1,3)*A(2,1)) B(3,3) = +detinv * (A(1,1)*A(2,2) - A(1,2)*A(2,1)) end function pure function matinv4(A) result(B) !! Performs a direct calculation of the inverse of a 4×4 matrix. complex(wp), intent(in) :: A(4,4) !! Matrix complex(wp) :: B(4,4) !! Inverse matrix complex(wp) :: detinv ! Calculate the inverse determinant of the matrix detinv = & 1/(A(1,1)*(A(2,2)*(A(3,3)*A(4,4)-A(3,4)*A(4,3))+A(2,3)*(A(3,4)*A(4,2)-A(3,2)*A(4,4))+A(2,4)*(A(3,2)*A(4,3)-A(3,3)*A(4,2)))& - A(1,2)*(A(2,1)*(A(3,3)*A(4,4)-A(3,4)*A(4,3))+A(2,3)*(A(3,4)*A(4,1)-A(3,1)*A(4,4))+A(2,4)*(A(3,1)*A(4,3)-A(3,3)*A(4,1)))& + A(1,3)*(A(2,1)*(A(3,2)*A(4,4)-A(3,4)*A(4,2))+A(2,2)*(A(3,4)*A(4,1)-A(3,1)*A(4,4))+A(2,4)*(A(3,1)*A(4,2)-A(3,2)*A(4,1)))& - A(1,4)*(A(2,1)*(A(3,2)*A(4,3)-A(3,3)*A(4,2))+A(2,2)*(A(3,3)*A(4,1)-A(3,1)*A(4,3))+A(2,3)*(A(3,1)*A(4,2)-A(3,2)*A(4,1)))) ! Calculate the inverse of the matrix B(1,1) = detinv*(A(2,2)*(A(3,3)*A(4,4)-A(3,4)*A(4,3))+A(2,3)*(A(3,4)*A(4,2)-A(3,2)*A(4,4))+A(2,4)*(A(3,2)*A(4,3)-A(3,3)*A(4,2))) B(2,1) = detinv*(A(2,1)*(A(3,4)*A(4,3)-A(3,3)*A(4,4))+A(2,3)*(A(3,1)*A(4,4)-A(3,4)*A(4,1))+A(2,4)*(A(3,3)*A(4,1)-A(3,1)*A(4,3))) B(3,1) = detinv*(A(2,1)*(A(3,2)*A(4,4)-A(3,4)*A(4,2))+A(2,2)*(A(3,4)*A(4,1)-A(3,1)*A(4,4))+A(2,4)*(A(3,1)*A(4,2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