! Alexander Sage
!Date: 11/8/11
!Homework 5
!Purpose: To find the temperature of different parts of a metal plate using a formula for distribution of heat
program heat_plate
implicit none

integer :: i, j
real, dimension(10,10) :: old_matrix    !putting in initial values to a matrix
real, dimension(10,10) :: new_matrix    !putting in initial values to a matrix
real :: a

old_matrix(:10, :1) = 20         !assigning initial values of the outside edge
old_matrix(10:, 1:) = 20
new_matrix(:10, :1) = 20
new_matrix(10:, 1:) = 20
a = 1

forall (i = 2:9, j = 2:9)  !setting everything else at room temperature
  old_matrix(i, j) = 50
end forall

old_matrix(3, 8) = 100           !assign the heat source

do while (a > .001)    !only running the relaxation method when there is a difference between old_matrix and new_matrix
    Forall (i=2:9, j=2:9)     !applying relaxation method to old_matrix and inputting the new numbers into new_matrix
      new_matrix(i, j) = 1.0/4.0*(old_matrix(i+1, j) + old_matrix(i-1, j) + old_matrix(i, j+1) + old_matrix(i, j-1))
    end Forall
  new_matrix(3, 8) = 100   !ensuring the point of heat source doesn't change
  a= abs(old_matrix(2, 2) - new_matrix(2, 2))  !setting a bound for when to stop running the program based on convergence
  write (*,*) new_matrix(5, 5), new_matrix(3, 8), new_matrix(1,1), new_matrix(2, 2) ! checking to see if it worked
  old_matrix = new_matrix         !the ends of the plate have a consistent 20, the point (3, 8) has a consistent 100
!  a = 0                          !but I can't seem to fix the do while so that it repeats until correct
end do

write(*,*) "The temperature of the spot in the middle of the plate (5,5) is", new_matrix(5, 5), "degrees Celsius"

stop
end program heat_plate

!WARNING: this program has a flaw in the calculation of a in the do while, so there will be an infinite loop
!
!