gpt4 book ai didi

matrix - 翻转矩阵 fortran

转载 作者:行者123 更新时间:2023-12-04 15:11:47 25 4
gpt4 key购买 nike

我想把我的矩阵倒过来。使得 T(1,1)=C(2,1)

我已经制作了这个程序,我发现了一个应该在线执行该操作的代码,即 C=T(2:1:-1, :) 但是当尝试获取值时C(1,1) 应该是 3 我得到 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

最佳答案

如果您分配正确大小的矩阵,那么一切都应该按预期工作。

比如这个程序

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

或者,如果您确实想使用 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

输出:

   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 开始计数。为了安全起见,始终在 lboundubound 的帮助下遍历数组内在函数,而不是像上面那样使用显式边界:

  do i = lbound(t, dim=1), ubound(t, dim=1)
write (*, *) t(i, :)
end do

关于matrix - 翻转矩阵 fortran,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40312979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com