next up previous contents
Next: Modules Up: Examples and Exercises Previous: Internal Subprograms

Arrays

 

Arrays and array operations have undergone extensive change in the new Fortran standard. In Fortran 90, it is possible to treat an array as a single object. This permits array-valued expressions such as C = A + B without the need for do loops that are required in Fortran 77 to process the elements of the arrays one at a time. Although such statements are notationally convenient and offer a more natural form of expression, they are also important in utilizing the high computational speeds of parallel and vector computers.gif Functions may now be array-valued, which was impossible to achieve in Fortran 77. Most intrinsic functions have been extended and act elementally on arrays, as do the intrinsic operators, such as `+' above.gif Array sections are obtained using a syntax similar to Matlab. A( :, i ) is the ith column of A. The `:' represents all elements in the extent of the particular dimension. A( 2:4, 3:5 ) is the tex2html_wrap_inline801 array obtained from rows 2 through 4 and columns 3 through 5 of A. A stride may also be specified, achieving an effect similar to the step of a do loop. For example, A( 2:10:2, 2:10 ) is the tex2html_wrap_inline803 array obtained from rows 2, 4, 6, 8, and 10 and columns 2 through 10 of A.

Passing arrays to subprograms is another area of improvement in the new standard. In Fortran 77, only the extents in the last dimension can be assumed in a subprogram. This often requires extending the argument list of a subprogram to include the extents of each dimension of the array. Fortran 90 supports assumed-shape arrays in dummy arguments in a subprogram. The extents can be determined by the subprogram through the use of the new intrinsic function size.gif These array processing features of Fortran 90 are illustrated by the MatrixVector program below.

program MatrixVector
   implicit none
   integer, parameter :: N = 3

   real, dimension( N, N ) :: A
   real, dimension( N ) :: b, c

   ! Fill A and b with random entries.
   call random_number( A )
   call random_number( b )

   ! Compute the matrix-vector product, A*b.
   c = matrixVectorMultiply( A, b )

   print *, 'The matrix-vector product is ', c

   contains 

   function matrixVectorMultiply( A, b ) result( c )
      implicit none

      ! Assume the shape of A and b.
      real, dimension( :, : ), intent( in ) :: A
      real, dimension( : ), intent( in ) :: b
      real, dimension( size( b ) ) :: c

      integer N
      integer i

      N = size( b )

      c = 0.0

      do i = 1, N
         c = c + b( i ) * A( :, i )
      end do
   end function matrixVectorMultiply

end program MatrixVector

  exercise185

exercise189

exercise192


next up previous contents
Next: Modules Up: Examples and Exercises Previous: Internal Subprograms