How does one 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
Use intrinsic functions REAL and AIMAG to write individual 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 character strings that have value '+i' when imaginary part is positive, and '-i' where imaginary part is negative. Because the negative imaginary part is accounted for in the formatting ('-i'), we take absolute value of the imaginary part. Edit the format descriptor accordingly so that the program you use to read the output file will be able to read it.