如果您分配正確大小的矩陣,那麼一切都應按預期工作。
例如,這個程序
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
產生以下輸出
1.0000000000000000 2.0000000000000000
3.0000000000000000 4.0000000000000000
3.0000000000000000 4.0000000000000000
1.0000000000000000 2.0000000000000000
或者,如果你真的想與3×3矩陣來工作,那麼這個錯誤是在該行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
輸出:
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
小心與陣列的計數元件。 Off-by-one errors可能很難調試,因此總是從0開始計數或總是從1開始計數。爲了安全起見,請在lbound
和ubound
內部函數的幫助下遍歷數組,而不是像上面那樣使用顯式邊界:
do i = lbound(t, dim=1), ubound(t, dim=1)
write (*, *) t(i, :)
end do
要從頭開始:您將矩陣'T'和'C'分配爲3x3大小而不是2x2。 – Wildcat