Reputation: 967
I'd be glad if somebody could help me with this. I'm studying modules in fortran, and I have a question. Let's say that my module creates a matrix [A(3,3)] that is read from user's input. Then, I'd like to use such a matrix in a new subroutine so that I can do an operation with it (for the sake of simplicity let's say a sum). My code looks like this:
module matrixm
contains
subroutine matrixc
integer i,j
real, DIMENSION(3,3) :: a
do 10 i=1,3
do 20 j=1,3
read(*,*) a(i,j)
20 continue
10 continue
end subroutine matrixc
end module matrixm
program matrix
use matrixm
real, dimension(3,3) :: b,c
integer i,j
call matrixc
b=10.0
c=a+b
write statements here...
end
If the input of A is: 1 2 3 4 5 6 7 8 9 one would expect C[3,3] to be 11 12 13 14 15 16 17 18 19. However, the result shows only a matrix C whose elemets are all of them equal to 10.0. What is the error I have in my program?, and much more important, am I correct on what's the use of a module?. I have a similar issue on a big problem I'm working on right now. Thanks.
Upvotes: 0
Views: 75
Reputation: 2518
The problem you have in your program is the visible memory:
You read the data in the matrix a
which is local to your subroutine matrixc
. This means, that this change is not visible to the program.
The next thing is, that the variable a
in your program is implicitely defined as real and as a result, doesn't throw an error (keyword: IMPLICIT NONE).
There are two easy solutions:
1: Put the definition of matrix a
in the definition part of your module:
module matrixm
REAL, DIMENSION(3,3) :: a
CONTAINS
subroutine matrixc
integer i,j
do i=1,3
do j=1,3
read(*,*) a(i,j)
end do
end do
end subroutine matrixc
end module matrixm
2: Use a
as a parameter to your subroutine and define it in the main program:
module matrixm
CONTAINS
subroutine matrixc(a)
integer i,j
REAL, DIMENSION(3,3) :: a
do i=1,3
do j=1,3
read(*,*) a(i,j)
end do
end do
end subroutine matrixc
end module matrixm
program matrix
use matrixm
IMPLICIT NONE
real, dimension(3,3) :: a,b,c
integer i,j
call matrixc(a)
b=10.0
c=a+b
write statements here...
end program
Upvotes: 1