Search code examples
matrixprintingfortranlinear-algebracomplex-numbers

Printing a complex matrix Fortran


The complex matrix is declared this way:

complex(8) :: matrix(:,:)

How can I print this matrix with each element as: (a, b) or a+ib, and in a nxn format? (by that I mean as a square matrix, with a row per line, so there will be n rows and n columns)

This is the way I would print a real matrix with the format I want:

do i=1,n
    do j=1,n
        write(*, fmt="(f0.2, tr2)", advance="no") matrix(i,j)
end do
    write(*, fmt="(a)") " "
end do

But I'm not sure how to translate this to a complex matrix


Solution

  • How can I print this matrix with each element as: (a, b)

    Supposing you already know that (a b) is the default printing fotmat for complex type, Why isn't this just enough?

    do j=1,n
      write(*, *) matrix(:,j)
    end do
    

    The output would be something like:

              (10.000000000000000,-20.000000000000000)              (10.000000000000000,-20.000000000000000)              (10.000000000000000,-20.000000000000000)
              (10.000000000000000, 20.000000000000000)              (10.000000000000000, 20.000000000000000)              (10.000000000000000, 20.000000000000000)
    

    If you want something more customized, you could try something like this (adjusting the field width and precision):

    do j=1,n
      write(*, "(*('('sf6.2xspf6.2x'i)':x))") matrix(:,j)
    end do
    

    That produces something like this:

    ( 10.00 -20.00 i) ( 10.00 -20.00 i) ( 10.00 -20.00 i)
    ( 10.00 +20.00 i) ( 10.00 +20.00 i) ( 10.00 +20.00 i)