在Fortran中将复杂矩阵写入文件 [英] Writing a complex matrix to a file in Fortran
问题描述
如何在Fortran中将复杂(n×n)矩阵写入文件? 例如:
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
在此示例中,将2n×n个元素写入文件,即实数和虚数. 代替两个元素Re(a11)Im(a11),我如何将其写为一个元素Re(a11)+ iIm(a11)?
In this example one gets 2n×n elements written to the file i.e. the real and imaginary. Instead of two element, Re(a11) Im(a11), How can I write it as one element Re(a11)+iIm(a11)?
推荐答案
使用内在函数REAL和AIMAG编写复数的各个实部和虚部:
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
说明:该代码定义了一个字符串矩阵,当虚部为正时,值为"+ i";当虚部为负时,值为"-i".因为负虚数部分在格式('-i')中占位,所以我们采用虚数部分的绝对值.相应地编辑格式描述符,以便您用于读取输出文件的程序将能够读取它.
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.
这篇关于在Fortran中将复杂矩阵写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!