Search code examples
oopfortranfortran2003derived-types

Is it possible to declare a matrix as a derived type in Fortran?


Is it possible to declare a matrix as a derived type in Fortran? For example, can something be done so that the call

class(four_by_four_matrix) :: A

call A%inv 

is valid? Where inv is declared as a procedure of four_by_four_matrix?


Solution

  • The answer to the question "is it possible?" is yes, it is possible. Just put a 2d array into your type:

      type four_by_four_matrix
        real(rp) :: arr(4,4)
      contains
        procedure :: inv => four_by_four_matrix_inv
      end type
    
    contains
    
      subroutine four_by_four_matrix_inv(self)
        class(four_by_four_matrix), intent(inout) :: self
        ....
        !somehow invert self%arr
      end subroutine
    
    end module
    
    ...
    
    type(four_by_four_matrix) :: A
    
    call A%inv
    

    If you need more details, you have to make a question with your actual detailed problems.

    BTW type-bound procedures and the class keyword were introduced in Fortran 2003. Notice you don't necessarily need to use class, you can also use type(four_by_four_matrix) if your variable is not polymorphic.