Reading and Writing Matrices

When matrix data is stored in a file, it is most convenient to store each row of the matrix in on line of the file. In addition, it is helpful, but not necessary, to store the dimensions of the matrix at the beginning of the file. This makes it easy to read the matrix. The example below shows a matrix with two rows and three columns as it would appear in the input stream. Note that it makes no difference whether it is read from the keyboard or a file. This is how the data would appear on the screen as it is typed, or in a text file opened with an editor.

        2 3
        10.4    5.8     -1.2
        0.6     3.9     8.3

With the file in this format, we can easily read the data into a two-dimensional array, remembering the "one statement equals one line" rule for reading input. That is, each line of the file must be read using a single read statement.

        !   Program description:
        !       Input a matrix from standard input and echo to standard output
        !   Modification history:
        !   Date        Name        Modification
        !   2011-03-26  Jason Bacon Begin
        ! Main program body
        program echo_matrix
            ! Disable implicit declarations (i-n rule)
            implicit none
            ! Variable definitions
            double precision, allocatable :: matrix(:,:)
            integer :: rows, cols, r, allocate_status, read_status
            ! Get size of matrix
            read *, rows, cols
            ! Allocate array to hold matrix
            allocate(matrix(1:rows, 1:cols), stat=allocate_status)
            if ( allocate_status /= 0 ) then
                print *, 'Error allocating ', rows, ' x ', cols, ' matrix.'
            ! Read matrix into the array
            do r = 1, rows
                read (*, *, iostat=read_status) matrix(r,1:cols)
            ! Print matrix to standard output
            do r = 1, rows
                print *, matrix(r,1:cols)
        end program