matrix in fortran
Fortran Matrix Operations
To perform matrix operations in Fortran, you can use arrays and built-in functions. Here's an example of how to create and manipulate matrices in Fortran:
program matrix_operations
implicit none
integer, parameter :: n = 3 ! size of the matrix
real :: matrix(n, n) ! declare a 3x3 matrix
! initialize the matrix
matrix = reshape([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], [n, n])
! print the matrix
write(, ) "Matrix:"
do i = 1, n
write(, ) matrix(i, :)
end do
! transpose the matrix
matrix = transpose(matrix)
! print the transposed matrix
write(, ) "Transposed Matrix:"
do i = 1, n
write(, ) matrix(i, :)
end do
! calculate the determinant of the matrix
write(, ) "Determinant:", determinant(matrix)
contains
! function to calculate the determinant of a matrix
real function determinant(mat)
real, intent(in) :: mat(n, n)
integer :: ipiv(n), info
! copy the matrix to a temporary variable
real :: temp(n, n)
temp = mat
! calculate the determinant using LAPACK routine
call sgetrf(n, n, temp, n, ipiv, info)
determinant = product(diag(temp))
end function determinant
end program matrix_operations
This program demonstrates how to create a 3x3 matrix, print it, transpose it, and calculate its determinant using the LAPACK routine sgetrf
. You can modify the size of the matrix by changing the value of n
.
Please note that this is just a basic example to illustrate matrix operations in Fortran. There are many other operations and functions available for matrix manipulation in Fortran, depending on your specific requirements.