Pages

30 March 2013

learning fortran

I've decided that a person with a science degree is probably lacking if s?he doesn't know a bit of Fortran, so I've taken the liberty of teaching myself by following the tutorial available a Fortran Tutorial. I ran into a bit of a snag on Exercise 6.3 on the Subroutines and Functions lesson. For some reason I couldn't get the subroutine to work the way I wanted. I knew the algorithm for the finite difference matrix itself was correct, but it kept crashing on me

I'm using gfortran on both my workstation and on my android device, but they both seem to work differently when it comes to arrays and fortran procedural programming and I think gcc on my android is broken. This only made things more frustrating for me, so I began to do a lot of reading on Fortran 95 and how it handles arrays, functions and the like while trying things out.

Happily, I was able to figure it out but it only works on my workstation. It's too bad the gcc android port I'm using is broken, I'll have to find a replacement. Anyhow, here is the code I was able to cobble together. Try not to be too critical.


program exercise6_3
    !print out a finite difference matrix using a function
    implicit none
    integer :: row, col, length
    integer, allocatable, dimension(:,:) :: matrix 
    print *, 'How big is your nxn matrix?'
    read *, length

    allocate(matrix(length, length))
    call d_matrix(length, matrix)

    do row = 1, length
          write(*, 10) (matrix(row, col), col = 1, length)
    end do

    10 format(100i2)

    deallocate(matrix)

    end program exercise6_3

    subroutine d_matrix(count, array)
    !finite difference matrix
        implicit none
        integer :: count, m
        integer, dimension(count,count) :: array
        !array dimensions must be specified

        array = 0
        do m = 1, count
              array(m, m) = 2
              if ( m /= count ) then
                    array(m, m + 1) = -1
                    array(m + 1, m) = -1
                end if
        end do

        end subroutine d_matrix