Writing a complex matrix to a file in Fortran
How to write a complex (n × n) matrix in Fortran to a file? For example:
DO I=1,N
write(14,'(100g15.5)') ( M(i,j), j=1,n )
ENDDO
In this example, each gets 2n × n elements written to the file, that is, real and imaginary. Instead of two elements, Re (a11) Im (a11), How can I write it as one element Re (a11) + iIm (a11)?
source to share
Use the internal REAL and AIMAG functions to record the separate real and imaginary components of a complex number:
CHARACTER(LEN=3),DIMENSION(n,n) :: imag_unit = '+i*'
WHERE(AIMAG(M)<0.)imag_unit = '-i*'
DO I=1,N
write(14,'(100(g15.5,a,g15.5,2x))') ( REAL(M(i,j)),imag_unit(i,j),&
ABS(AIMAG(M(i,j))), j=1,n )
ENDDO
Explanation: This code defines a matrix of characters that have the value "+ i" when the imaginary part is positive and "-i" where the imaginary part is negative. Since the negative imaginary part is included in the formatting ('-i'), we accept the absolute value of the imaginary part. Change the format descriptor appropriately so that the program you used to read the output file can read it.
source to share