urs*_*oth 2 fortran matrix gfortran fortran90
我想翻转我的矩阵。使得 T(1,1)=C(2,1)
我已经制作了这个程序,我发现了一个应该在线完成的代码,C=T(2:1:-1, :)但是当尝试获得应该是 3 的值 C(1,1) 时,我得到 1.3533635457363350E-306。你如何翻转矩阵使得向上变成向下?
program main
implicit none
integer iMax, jMax
double precision, dimension(:,:), allocatable :: T,C
double precision x, dx,f,L2old,L2norm
integer i, j,n
allocate(T(0:2, 0:2))
allocate(C(0:2, 0:2))
T(1,1)=1
T(1,2)=2
T(2,1)=3
T(2,2)=4
write(*,*) T(2,2)
C=T(2:1:-1, :)
Write(*,*) C(1,2)
end program main
Run Code Online (Sandbox Code Playgroud)
如果您分配大小合适的矩阵,那么一切都应该按预期工作。
例如,这个程序
program main
implicit none
double precision, dimension(:, :), allocatable :: t, c
integer :: i
allocate (t(1:2, 1:2))
allocate (c(1:2, 1:2))
t = reshape([1, 3, 2, 4], shape(t))
do i = 1, 2
write (*, *) t(i, :)
end do
write (*, *) ""
c = t(2:1:-1, :)
do i = 1, 2
write (*, *) c(i, :)
end do
end program main
Run Code Online (Sandbox Code Playgroud)
产生以下输出
1.0000000000000000 2.0000000000000000
3.0000000000000000 4.0000000000000000
3.0000000000000000 4.0000000000000000
1.0000000000000000 2.0000000000000000
Run Code Online (Sandbox Code Playgroud)
或者,如果您确实想使用 3x3 矩阵,那么错误就在C=T(2:1:-1, :). 应该是C=T(2:0:-1, :)。
program main
implicit none
double precision, dimension(:, :), allocatable :: t, c
integer :: i
allocate (t(0:2, 0:2))
allocate (c(0:2, 0:2))
t = reshape([1, 4, 7, 2, 5, 8, 3, 6, 9], shape(t))
do i = 0, 2
write (*, *) t(i, :)
end do
write (*, *) ""
c = t(2:0:-1, :)
do i = 0, 2
write (*, *) c(i, :)
end do
end program main
Run Code Online (Sandbox Code Playgroud)
输出:
1.0000000000000000 2.0000000000000000 3.0000000000000000
4.0000000000000000 5.0000000000000000 6.0000000000000000
7.0000000000000000 8.0000000000000000 9.0000000000000000
7.0000000000000000 8.0000000000000000 9.0000000000000000
4.0000000000000000 5.0000000000000000 6.0000000000000000
1.0000000000000000 2.0000000000000000 3.0000000000000000
Run Code Online (Sandbox Code Playgroud)
计算数组元素时要小心。关闭接一个错误可能是调试相当困难的,所以最好总是从0从1的帮助下开始计数或始终并成为在安全方面始终遍历数组lbound和ubound内部函数,而不是使用明确的界限,因为它是以上完成:
do i = lbound(t, dim=1), ubound(t, dim=1)
write (*, *) t(i, :)
end do
Run Code Online (Sandbox Code Playgroud)