Advertisement
Guest User

MatrixMultiplicationAndTranspose

a guest
Jun 23rd, 2019
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. dimension A(10,10),B(10,10),C(10,10),Btranspose(10,10),AB(10,10),ABBtranspose(10,10),ABBtransposeB(10,10)
  2.     arow=3
  3.     acol=3
  4.     brow=3
  5.     bcol=2
  6.     open(5,file='A.txt')
  7.     do i=1,arow
  8.         read (5,*)(A(i,j),j=1,acol)
  9.     end do
  10.     open(5,file='B.txt')
  11.     do i=1,brow
  12.         read (5,*)(B(i,j),j=1,bcol)
  13.     end do
  14.    
  15.     !Do [A][B][B]'[B]
  16.     call MatMul(A,B,AB,arow,acol,brow,bcol)
  17.     call Transpose(B,Btranspose,brow,bcol)
  18.     call MatMul(AB,Btranspose,ABBtranspose,arow,bcol,bcol,brow)
  19.     call MatMul(ABBtranspose,B,ABBtransposeB,arow,brow,brow,bcol)
  20.    
  21.     do i=1,arow
  22.         write (*,*)(ABBtransposeB(i,j),j=1,bcol)
  23.     end do
  24.     end program
  25.    
  26.    
  27. subroutine Transpose(A,R,rows,cols)
  28. dimension A(10,10),R(10,10) !CAUTION: This declaration is crucial
  29.     do i=1,cols !i goes from 1 to cols
  30.         do j=1,rows !and j from 1 to rows because transpose should have the dimension: cols x rows
  31.             R(i,j)=A(j,i) !fills from column of A to row of R
  32.         end do
  33.     end do
  34.     return
  35. end subroutine Transpose
  36.    
  37.    
  38. subroutine MatMul(A,B,C,arow,acol,brow,bcol)
  39. !To see how this works, try writing the elements of the product matrix in sigma notation
  40. dimension A(10,10),B(10,10),C(10,10) !CAUTION: This declaration is crucial
  41. do k=1,arow !k runs from 1 to arow
  42.     do l=1,bcol !and l from 1 to bcol because that's the output matrix dimension and we _have_ to populate each element of it
  43.         sum=0
  44.         do i=1,acol !this loop is the essence of the aforementioned sigma notation for the (k,l) element of the product matrix
  45.             sum=sum+A(k,i)*B(i,l)
  46.         end do
  47.         C(k,l)=sum
  48.     end do
  49. end do
  50. return
  51. end subroutine MatMul
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement