Fortran: Fortran 95: Vektoren- und Matrizenrechnung

Aus Wikibooks
<<< zur Fortran-Startseite
<< Fortran 95 Fortran 2003 >>
< Zeiger Systemroutinen >


In Fortran95 können einige elementare Vektoren- und Matrizenoperationen sehr einfach ausgeführt werden.


Beispiel: Addition und Subtraktion von Vektoren (Matrizen)

Fortran 90/95-Code (free source form)
program bsp
  implicit none
 
  real, dimension(3) :: a = (/3, 2, -5/), b = (/1, -3, -1/)
     
  write(*,*) "a+b: ", a+b
  ! Ausgabe:  a+b:  4. -1. -6.
 
  write(*,*) "a-b: ", a-b 
  ! Ausgabe: a-b:  2. 5. -4.
end program bsp


Beispiel: Multiplikation eines Vektors (einer Matrix) mit einem Skalar

Fortran 90/95-Code (free source form)
program bsp
  implicit none
 
  real, dimension(3) :: a = (/3, 2, -5/)
     
  write(*,*) "3.5*a: ", 3.5*a
  ! Ausgabe: 3.5*a:  10.5 7. -17.5
end program bsp


Beispiel: Skalarprodukt

Fortran 90/95-Code (free source form)
program bsp
  implicit none
 
  real, dimension(3) :: a = (/3, 2, -5/), b = (/1, -3, -1/)
  real               :: dot_product
     
  write(*,*) "a.b: ", dot_product(a, b)
  ! Ausgabe: 2
end program bsp


Beispiel: Euklidische Norm eines Vektors

Fortran 90/95-Code (free source form)
program bsp
  implicit none
 
  real, dimension(3) :: x = (/3, 2, -5/)
  real               :: x_n
  
  ! Norm des Vektors x  
  x_n = sqrt(sum(x**2))
      
  write(*,*) "Die Norm des Vektors (", x, ") beträgt: ", x_n
  ! Ausgabe: Die Norm des Vektors ( 3.0  2.0 -5.0 ) beträgt:  6.164414
end program bsp


Beispiel: Matrizenmultiplikation

Fortran 90/95-Code (free source form)
program bsp
  implicit none
 
  real, dimension(3,2) :: A = reshape( (/3., 2., 1., 1., 1., 2.5/), (/3, 2/) )
  real, dimension(2,2) :: B = reshape( (/1., -3., -1., 5./), (/2, 2/) )
  real, dimension(3,2) :: C
  
  C = matmul(A, B)  
   
  write(*,*) "Matrix C ="
  write(*,*) C(1, :)
  write(*,*) C(2, :)
  write(*,*) C(3, :)
  ! Ausgabe: Matrix C =
  !           0.000000       2.000000
  !           -1.000000      3.000000
  !           -6.500000      11.50000
end program bsp


Beispiel: Transponierte Matrix

Fortran 90/95-Code (free source form)
program bsp
  implicit none
 
  real, dimension(2,2) :: A = reshape( (/3., 2., 1., -1.5/), (/2, 2/) ), AT
  
  AT = transpose(A)  
  
  write(*,*) "A ="
  write(*,*) A(1, :)
  write(*,*) A(2, :)
  ! Ausgabe: A =
  ! 3.000000       1.000000
  ! 2.000000      -1.500000
   
  write(*,*) "AT ="
  write(*,*) AT(1, :)
  write(*,*) AT(2, :)
  ! Ausgabe: AT =
  ! 3.000000       2.000000
  ! 1.000000      -1.500000   
end program bsp

<<< zur Fortran-Startseite
<< Fortran 95 Fortran 2003 >>
< Zeiger Systemroutinen >