next up previous
Next: Numerical Representation Up: Arrays and subroutines Previous: Arrays and subroutines

Variable Dimensioning

Fortran (f77) does not allow for dynamic allocation of memory. That means that you have to declare array sizes at compile time. One way around this problem is illustrated in the following code.

           program check_mats
        implicit none
        integer i,j, nelt
        parameter (nelt=4)
        real A(nelt,nelt),x(nelt),b(nelt)

c      DEFINE THE MATRIX  A  VIA A DOUBLE LOOP
      do j=1,nelt
        do i = 1,nelt
          A(i,j)=0.0
          if (i .eq. j) then
            A(i,j)=2.0
          endif
        enddo
        x(j)=j
      end do

c      CALL SUBROUTINE TO PERFORM THE MULTIPLICATION
      call matmul(A,x,b,nelt)

c      DUMP OUT THE RESULT
      do i=1,nelt
        write(*,*)"b(",i,") = ",b(i)
      enddo

      end

      subroutine matmul(Mat,vin,vout,nelt)
      implicit none
      integer i, j, nelt
      real vin(nelt), vout(nelt), Mat(nelt,nelt)

      do i=1,nelt
        vout(i)=0.0
        do j = 1,nelt
          vout(i)=vout(i)
     1            +Mat(i,j)*vin(j)
        enddo
      end do

      return
      end
Note in particular that the parameter `nelt' is specified before the dimensions of A, x, b are given. If you assigned a large size to A, x, b (say 100) and then tried to pass the actual size (4) to the subroutine, the code would crash. If you wanted to be able to change dimensions without a recompile, you could read in a "header file" by creating another file (IN THE SAME DIRECTORY) called, say, hfl.h and changing the declarations to read
}
             program check_mats
        implicit none
        integer i,j
        include 'hfl.h'
        real A(nelt,nelt),x(nelt),b(nelt)



E. Bruce Pitman
Tue Sep 15 18:15:17 EDT 1998