Matrix fortran语言中的乘法乘积
我需要从我从计算机上的一个文件中得到的矩阵中,取两行的乘积,然后显示结果。我需要用子程序来做计算。我使用以下代码:Matrix fortran语言中的乘法乘积,matrix,fortran,Matrix,Fortran,我需要从我从计算机上的一个文件中得到的矩阵中,取两行的乘积,然后显示结果。我需要用子程序来做计算。我使用以下代码: program getting_result integer matrix(10,10),err,columns,i,j,rows,result open(1,file='C:/Users/User/matrix.txt',status='old',iostat=err) if (err/=0) then print *, 'Error opening file
program getting_result
integer matrix(10,10),err,columns,i,j,rows,result
open(1,file='C:/Users/User/matrix.txt',status='old',iostat=err)
if (err/=0) then
print *, 'Error opening file'
stop
endif
read (1,*) rows,columns
print *, rows,columns
do i=1,rows
do j=1,columns
read (1,*) matrix(i,j)
enddo
enddo
do i=1,rows
do j=1,columns
print 2, matrix(i,j)
enddo
print *, ' '
enddo
2 format(1x,I3,\)
call search(matrix,columns,rows,result)
print *, 'Result: ', result
read *
end
我不知道我需要在子程序中编写什么来选择并使用“read”方法乘法2行(我认为):
下面的代码读入一个矩阵并将该矩阵的两行相乘
program getting_result
implicit none
integer :: nrows, ncols, ios, rows(2), i, iounit
integer, allocatable :: matrix(:,:)
print *, 'nrows, ncols: '
read (*, *) nrows, ncols
allocate (matrix(nrows,ncols))
open (newunit=iounit, file='matrix.txt', action='read', iostat=ios)
if (ios /= 0) error stop "Error opening file"
do i = 1, nrows
read (iounit, *) matrix(i,:)
end do
close (unit=iounit, iostat=ios)
if (ios /= 0) error stop "Error closing file"
print *, 'Which rows to multiply?'
read (*, *) rows
print *, 'result:', dot_product(matrix(rows(1),:), matrix(rows(2),:))
end
我使用以下矩阵作为测试(结果来自八度音阶的magic(5)
)
$cat matrix.txt
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
程序给出以下输出
$gfortran-O3-Wall-fcheck=all-ga.f90&./a.out
nrows、NCOL:
5 5
要乘哪一行?
1 2
结果:870
通常情况下,在数据文件的第一行中包含矩阵维度,而不是从命令行中读取,但我尽量靠近您的初始程序。请详细说明过程
搜索
应该做什么。哪两行应该相乘?@jack我需要将程序启动后使用方法read
写入的索引行相乘。我没有把它写在这里,因为我不确定我必须把它放在哪里
program getting_result
implicit none
integer :: nrows, ncols, ios, rows(2), i, iounit
integer, allocatable :: matrix(:,:)
print *, 'nrows, ncols: '
read (*, *) nrows, ncols
allocate (matrix(nrows,ncols))
open (newunit=iounit, file='matrix.txt', action='read', iostat=ios)
if (ios /= 0) error stop "Error opening file"
do i = 1, nrows
read (iounit, *) matrix(i,:)
end do
close (unit=iounit, iostat=ios)
if (ios /= 0) error stop "Error closing file"
print *, 'Which rows to multiply?'
read (*, *) rows
print *, 'result:', dot_product(matrix(rows(1),:), matrix(rows(2),:))
end