Matrix Operations
A matrix in mathematics can be represented by an array in FORTRAN. FORTRAN 90/95 provides some functions which conveniently use an array as a whole without subscripts. In order to understand how the matrix operations are performed, we only use array subscripts and DO Loops in the example programs.
REAL x(5,5) !declare x as a
2D array
Do 10 I=1,5
Do 10 J=1,5
Read(*,*) x(I,J)
! read 5x5=25 data from keyboard
10 continue
REAL x(5,5), y(5,5),
z(5,5)
! z is the sum of x and y
Do 10 I=1,5
Do 10 J=1,5
Z(I,J)=x(I,J)+y(I,J)
10 continue
REAL x(5,5), y(5,5),
z(5,5)
! z is the multiplication of x and y
Do 10 I=1,5
Do 10 J=1,5
Z(I,J)=0
Do 20 K=1,5
Z(I,J)=z(I,J)+x(I,K)*y(K,J)
20 continue
10 continue
4. To display a 5x5 matrix with 5 rows and 5 columns
REAL
x(5,5)
Do
10 I=1,5
Write(*, 1000) (x(I,J), J=1,5) ! write 5
numbers on one row
10
continue
1000
format(5f10.3)
Exercises
1. Write the output of the program. What are the values stored in x(3), y(3), prod(1,3), prod(3,3) and prod(5,3)?
Program matrix1
Real x(0:5), y(0:5)
integer prod(5,5)
do 10 i = 0, 5
x(i) = 2.0*i
y(i) = 2.0*i
+ 1.0
write(*,*)
x(i)+ y(i)
10 continue
Do 100 i = 1, 5
Do
100 j = 1, 5
prod(i,j) = i*j
100 continue
do 300 k = 1, 5
write(*,*) prod(k,k)
300 continue
stop
end program matrix1
2. If 1,2,3….16 are the numbers input from the keyboard to the following program segment, what are the values stored in x(1,1), x(2,3) and x(3,0)?
REAL x(0:3,0:3) !declare x as a
2D array
Do 10 I=0,3
Do 10 J=0,3
Read(*,*) x(I,J)
! read data from keyboard
10 continue
3. Write a program (mprod.f95) to do multiplication of two-3x3 matrices. In the program, two 3x3 matrices of real numbers are entered via keyboard; and the result of the multiplication of the two 3x3 matrices is displayed on the computer screen (1 decimal place) and saved in a file (result.dat).
For example:
Output on screen:
3.0 6.0 10.0
6.0 14.0 25.0
10.0 25.0 46.0