Silverfrost Forums

Welcome to our forums

Matrix subtraction

14 Jan 2012 8:12 #9464

I am using FTN 95 express downloaded from the site.

Is there anny intrinsic function to carry out matrix subtraction in FTN 95 than using the do loop?

I saw we have an intrinsic function SUM for summing arrays/matrices. Though i can negate a matrix and use SUM for subtraction, is there a direct function?

15 Jan 2012 6:14 #9465

Array syntax can be used for addition and subtraction. MATMUL intrinsic function can be used for multiplication. There are probbly many matrix inversion functions available in public domain fortran 90+ libraries for division (multiply by the inverse). The code below compares F90+ array syntax to F77 DO loop approach. You need to make sure that the array dimensions are compatible with the operation.

!     Last change:  JDC  15 Jan 2012    5:07 pm
      integer*4, parameter :: m     = 8
      integer*4, parameter :: n     = 7
      real*8,    parameter :: two   = 2
      real*8,    parameter :: three = 3
!
      real*8     a(m,n), b(m,n), c(n,m), aa(m,n), d(m,m)
      real*10    s, e, emax
      integer*4  i,j
!
      forall (i=1:m,j=1:n)
        a(i,j) = real(i*2+j)
        b(i,j) = real(j-i)
        c(j,i) = real(j-i)
      end forall
!
!  Addition
      aa = two * a + three * b       ! array syntax
!
      emax = 0
      do i = 1,m
         do j = 1,n
            s = two * a(i,j) + three * b(i,j)
            e = abs (aa(i,j) - s)
            emax = max (emax,e)
         end do
         write (*,1001) aa(i,:)
      end do
      write (*,*) 'Max error in addition =',emax
!
!  Multiplication
      d = matmul (a, c)             ! array syntax
!
      emax = 0
      do i = 1,m
         do j = 1,m
            s = dot_product (a(i,:), c(:,j))
            e = abs (d(i,j) - s)
            emax = max (emax,e)
         end do
         write (*,1001) d(i,:)
      end do
      write (*,*) 'Max error in multiplication =',emax
!
1001  format (10f8.1)
      end
15 Jan 2012 7:48 #9466

Thanks a lot for the reply.

So, in FTN 95 express, for subtraction if I have:

real*8 A(5,5),B(5,5),C(5,5)
! ----- some code
!------- some code

C=A-B

IS this right?

15 Jan 2012 7:52 #9468

Also, what does the intrinsic function SUM do?

15 Jan 2012 8:28 #9469

Yes that is right. The Fortran 90 standard provides for element by element addition and subtraction etc.

The effect of the Fortran 90 intrinsic SUM can be found in the FTN95 help file (as well as in the Fortran standard and many books).

Please login to reply.