FORTRAN95矩阵运算:乘积和逆矩阵求解
以下是使用FORTRAN95编写的求矩阵乘积和逆矩阵的示例代码:
program matrix_operations
implicit none
integer, parameter :: n = 3 ! 矩阵的维数
real :: mat1(n,n), mat2(n,n), product(n,n) ! 矩阵和乘积
real :: determinant ! 行列式的值
real :: inv_mat(n,n) ! 逆矩阵
! 初始化矩阵 mat1 和 mat2
mat1 = reshape([1, 2, 3, 4, 5, 6, 7, 8, 9], [n,n])
mat2 = reshape([9, 8, 7, 6, 5, 4, 3, 2, 1], [n,n])
! 计算矩阵乘积
call matrix_multiply(mat1, mat2, product)
! 输出矩阵乘积
write(*,*) 'Matrix product:'
do i = 1, n
write(*, '(3F5.1)') product(i,:)
end do
! 计算矩阵的逆矩阵
call matrix_inverse(mat1, inv_mat, determinant)
! 输出逆矩阵
write(*,*) 'Matrix inverse:'
do i = 1, n
write(*, '(3F5.1)') inv_mat(i,:)
end do
! 输出行列式的值
write(*,*) 'Determinant:', determinant
contains
subroutine matrix_multiply(mat1, mat2, product)
implicit none
integer, parameter :: n = 3 ! 矩阵的维数
real, intent(in) :: mat1(n,n), mat2(n,n) ! 输入矩阵
real, intent(out) :: product(n,n) ! 乘积矩阵
integer :: i, j, k
do i = 1, n
do j = 1, n
product(i,j) = 0.0
do k = 1, n
product(i,j) = product(i,j) + mat1(i,k) * mat2(k,j)
end do
end do
end do
end subroutine matrix_multiply
subroutine matrix_inverse(mat, inv_mat, determinant)
implicit none
integer, parameter :: n = 3 ! 矩阵的维数
real, intent(in) :: mat(n,n) ! 输入矩阵
real, intent(out) :: inv_mat(n,n) ! 逆矩阵
real, intent(out) :: determinant ! 行列式的值
real :: temp_mat(n,n), temp_vec(n), factor
integer :: i, j, k
! 初始化临时矩阵和向量
temp_mat = mat
temp_vec = 0.0
! 使用高斯-约当消元法计算逆矩阵
determinant = 1.0
do k = 1, n
temp_vec = 0.0
temp_vec(k) = 1.0
do i = 1, n
if(temp_mat(i,i) == 0.0) then
factor = 0.0
write(*,*) 'Error: Matrix is singular!'
stop
end if
factor = temp_mat(i,i)
determinant = determinant * factor
temp_mat(i,:) = temp_mat(i,:) / factor
temp_vec(i) = temp_vec(i) / factor
do j = 1, n
if(j /= i) then
factor = temp_mat(j,i)
temp_mat(j,:) = temp_mat(j,:) - factor * temp_mat(i,:)
temp_vec(j) = temp_vec(j) - factor * temp_vec(i)
end if
end do
end do
inv_mat(:,k) = temp_vec
end do
end subroutine matrix_inverse
end program matrix_operations
这个示例程序计算了两个3x3矩阵的乘积并求出了第一个矩阵的逆矩阵。首先,我们定义了一个程序 matrix_operations,其中包含了两个子程序 matrix_multiply 和 matrix_inverse。
子程序 matrix_multiply 接受两个输入矩阵 mat1 和 mat2,并将它们的乘积存储在 product 中。它使用了三个嵌套的循环来计算矩阵乘积。
子程序 matrix_inverse 接受一个输入矩阵 mat,并计算它的逆矩阵存储在 inv_mat 中。它还返回行列式的值 determinant。该子程序使用了高斯-约当消元法来计算逆矩阵。它首先初始化一个临时矩阵 temp_mat 和一个临时向量 temp_vec,然后对每一列应用消元法来计算逆矩阵。
在主程序中,我们初始化了两个输入矩阵 mat1 和 mat2,并调用子程序 matrix_multiply 和 matrix_inverse 来计算乘积矩阵和逆矩阵。最后,我们输出乘积矩阵、逆矩阵和行列式的值。
请注意,这个示例程序假定输入矩阵是3x3的。如果需要处理不同维数的矩阵,可以修改参数 n 的值,并相应地修改代码。
原文地址: https://www.cveoy.top/t/topic/o1U1 著作权归作者所有。请勿转载和采集!