Mothy
Mothy

Reputation: 23

Matrix generation in Fortran

The problem: I need to generate a M*N matrix, where M is for rows, N is for columns. Elements of this matrix should be like (i-1.0)*N+j. This code doesn't work and I can't understand why. I use Compaq Visual Fortran 6.

I except that this code must generate a matrix. After generation the matrix should be printed like

1.0 2.0 3.0

4.0 5.0 6.0

as for 3*2 matrix.

Now this code simply doesn't work, showing me a cpoule of Windows Executing Errors.

INTEGER M, N, I, J
COMMON /BLK1/ MATA (256, 256)
READ (7, 100) M
READ (7, 100) N
100 FORMAT (I3)
CALL MATGEN (M, N)
DO 90003 I = 1, M
DO 90004 J = 1, N
WRITE (8, 101) MATA(I, J)
101 FORMAT (F8.1, ' ', \)
90004 CONTINUE
WRITE (8, 102)
102 FORMAT (/, /)
90003 CONTINUE
END



SUBROUTINE MATGEN (M, N)
REAL DUM
INTEGER I, J
COMMON /BLK1/ MATA (256, 256)
DUM = 1.0
DO 90001 I = 1, M
DO 90002 J = 1, N
MATA (I, J) = DUM + 1.0
90002 CONTINUE
90001 CONTINUE
RETURN
END

COMMON BLK1
REAL MATA (256, 256)
END

Upvotes: 0

Views: 486

Answers (1)

Alexander Vogt
Alexander Vogt

Reputation: 18118

There are a couple of issues with your code:

  • The program does not really start (in the code below this is PROGRAM TEST)
  • MATA is (implicitly) an integer. I added the declaration. Please use IMPLICIT NONE in the future!
  • There is some weird code at the end that doesn't really belong there...
  • As francescalus noted, the assignment is not incremented, so MATA is filled with 2.
  • My version of gfortran does not accept the backslash to inhibit the line break. I had to use $. See here for details.
  • Agentp remarked that you do not open unit seven for input. I changed that lines to read from STDIN instead.
  • Indentation does not hurt!
      PROGRAM TEST
      IMPLICIT NONE
      INTEGER M, N, I, J
      REAL MATA
      COMMON /BLK1/ MATA(256, 256)
      WRITE(*,*) 'Please enter M:'
      READ (*, 100) M
      WRITE(*,*) 'Please enter N:'
      READ (*, 100) N
100   FORMAT (I3)

      CALL MATGEN (M, N)
      DO 90003 I = 1, M
        DO 90004 J = 1, N
          WRITE (8, 101) MATA(I, J)

101   FORMAT (F8.1, ' ', $)
90004   CONTINUE
        WRITE (8, 102)
102   FORMAT (/, /)
90003 CONTINUE
      END

      SUBROUTINE MATGEN (M, N)
      IMPLICIT NONE
      INTEGER M, N
      REAL DUM
      INTEGER I, J
      REAL MATA
      COMMON /BLK1/ MATA(256, 256)
      DUM = 0.0
      DO 90001 I = 1, M
        DO 90002 J = 1, N
          DUM = DUM + 1.
          MATA (I, J) = DUM
90002   CONTINUE
90001 CONTINUE
      RETURN
      END

This results in:

$ ./a.out 
 Please enter M:
2
 Please enter N:
3

$ cat fort.8 
     1.0      2.0      3.0 


     4.0      5.0      6.0 

Upvotes: 2

Related Questions