Silverfrost Forums

Welcome to our forums

variable format specifications?

28 Jan 2021 2:27 #26984

I am a beginner who is refreshing his memory of Fortran from a long time ago. Question: I am writing a short program to print an identity matrix where the dimension of the matrix is variable and is specified as a user input. This I can do okay. For the output I want to use a Write statement with a suitable Format statement. Something like Format(ni3) where n is a variable. However, it does not appear that Fortran allows the n to be a integer variable? I am just asking here to confirm this and that there is no work-around? The n has to be specified as an integer in the Format statement unless we are choosing 1?

28 Jan 2021 3:01 #26985

The fortran standard does not support (ni3) or (<n>i3) which was a dec/vax fortran extension. The best approach is use a DO loop and write 1 row at a time. What is a 'row' and what is a 'column' can be arbitrary, especially for a symmetric matrix. The following is a mix of old and new Fortran, which may prompt your memory. Fortran 90 introduced free format, array syntax and ALLOCATE, which were three of the best changes to old Fortran. program print_array real, allocatable :: array(:,:) integer :: n, i

  11  write (*,*) 'give n ?'
      read (*,*) n
      if ( n<1 .or. n>22) then
        write (*,*) ' can't use this n, try again '
        if ( n>=0 ) goto 11
      else
        allocate (array(n,n))
        array = 0
        do i = 1,n ; array(i,i) = 1 ; end do
        call write_array (array,n)
      end if
      end program print_array
      
      subroutine write_array (array,n)
      integer :: n, i
      real    :: array(n,n)
      do i = 1,n
        write (*,fmt='(22f10.2)') array(i,:)
      end do
      end subroutine write_array 
28 Jan 2021 4:16 #26986

Thanks for your reply with the short code example. It was very helpful and easy to understand. I am moving on to practicing subroutines next so it was also very timely.

After my original post I also tried just making n a big number in the original Format statement and, of course, it did work. Also, thanks for using the fmt format trick in your example. I encountered it in some of the documentation I came across researching my original question. I did not understand it at the time but I do now.

Please login to reply.