How to write the formatted matrix in a lines with

2019-09-05 01:19发布

Suppose I have the matrix c(i,j). I want to write it on the screen on oldest Fortran77 language with three signs after comma. I write

         do i=1,N
         write(*,"(F8.3)") ( c(i,j), j=1,N )
         end do

but the output is in the form

c(1,1)

c(1,2)

...

c(1,10) c(2,1)

c(2,2)

...

Finally, I may simply write

         do i=1,N
         write(*,*) ( c(i,j), j=1,N )
         end do

and then the output is like the matrix, but, of course, it is not formatted.

How to get the correct output in Fortran77?

An edit. It seems that one of solutions is to write

   do i=1, N
   do j=1, N
    write(*,'(F9.3,A,$)') c(i,j), ' '
   end do
    write(*,*) ' '
   end do

1条回答
SAY GOODBYE
2楼-- · 2019-09-05 01:52

Your format only specifies a single float but you actually want to write N per line.

A fairly general solution for this simple case would be something like

  program temp
  implicit none
  integer, parameter :: N=3
  real, dimension(N,N) :: c
  integer :: i,j
  character(len=20) :: exFmt
  c = 1.0
  write(exFmt,'("(",I0,"(F8.3))")') N
  do i=1,N
     write(*,exFmt) (c(i,j), j=1,N)
  end do
  end program

This will make exFmt be '(3(F8.3))', which specifies printing three floats (note you probably really want '(3(F8.3," "))' to explicitly include some spacing).

Note some compilers will allow for exFmt to be just '(*(F8.3))'. This is part of the fortran 2008 specification so may not be provided by all compilers you have access to. See here for a summary of compiler support (see Unlimited format item, thanks to HighPerformanceMark for this)

Finally an easy bodge is to use a format statment like '(1000(F8.3))' where 1000 is larger than you will ever need.

查看更多
登录 后发表回答