- Fortran - Home
- Fortran - Overview
- Fortran - Environment Setup
- Fortran - Basic Syntax
- Fortran - Data Types
- Fortran - Variables
- Fortran - Constants
- Fortran - Operators
- Fortran - Decisions
- Fortran - Loops
- Fortran - Numbers
- Fortran - Characters
- Fortran - Strings
- Fortran - Arrays
- Fortran - Dynamic Arrays
- Fortran - Derived Data Types
- Fortran - Pointers
- Fortran - Basic Input Output
- Fortran - File Input Output
- Fortran - Procedures
- Fortran - Modules
- Fortran - Intrinsic Functions
- Fortran - Numeric Precision
- Fortran - Program Libraries
- Fortran - Programming Style
- Fortran - Debugging Program
Fortran - Vector and Matrix Multiplication Functions
The following table describes the vector and matrix multiplication functions:
| Function | Description |
|---|---|
| dot_product(vector_a, vector_b) | This function returns a scalar product of two input vectors, which must have the same length. |
| matmul (matrix_a, matrix_b) | It returns the matrix product of two matrices, which must be consistent, i.e. have the dimensions like (m, k) and (k, n) |
Example
The following example demonstrates dot product:
program arrayDotProduct
real, dimension(5) :: a, b
integer:: i, asize, bsize
asize = size(a)
bsize = size(b)
do i = 1, asize
a(i) = i
end do
do i = 1, bsize
b(i) = i*2
end do
do i = 1, asize
Print *, a(i)
end do
do i = 1, bsize
Print *, b(i)
end do
Print*, 'Vector Multiplication: Dot Product:'
Print*, dot_product(a, b)
end program arrayDotProduct
When the above code is compiled and executed, it produces the following result:
1.00000000 2.00000000 3.00000000 4.00000000 5.00000000 2.00000000 4.00000000 6.00000000 8.00000000 10.0000000 Vector Multiplication: Dot Product: 110.000000
Example
The following example demonstrates matrix multiplication:
program matMulProduct
integer, dimension(3,3) :: a, b, c
integer :: i, j
do i = 1, 3
do j = 1, 3
a(i, j) = i+j
end do
end do
print *, 'Matrix Multiplication: A Matrix'
do i = 1, 3
do j = 1, 3
print*, a(i, j)
end do
end do
do i = 1, 3
do j = 1, 3
b(i, j) = i*j
end do
end do
Print*, 'Matrix Multiplication: B Matrix'
do i = 1, 3
do j = 1, 3
print*, b(i, j)
end do
end do
c = matmul(a, b)
Print*, 'Matrix Multiplication: Result Matrix'
do i = 1, 3
do j = 1, 3
print*, c(i, j)
end do
end do
end program matMulProduct
When the above code is compiled and executed, it produces the following result:
Matrix Multiplication: A Matrix 2 3 4 3 4 5 4 5 6 Matrix Multiplication: B Matrix 1 2 3 2 4 6 3 6 9 Matrix Multiplication: Result Matrix 20 40 60 26 52 78 32 64 96
fortran_arrays.htm
Advertisements