matrix - 翻转矩阵 fortran

标签 matrix fortran fortran90 gfortran

我想把我的矩阵倒过来。使得 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/

相关文章:

arrays - c_loc() 与动态数组

fortran - 使用拒绝方法创建正态分布会产生错误的前因子

fortran - 在 Fortran 中调用子例程(段错误)

arrays - 指针数组

MATLAB:比较两个数组的所有元素

python - 如何在 Theano 中进行 "generalized"矩阵运算?

c# - 如何在 C# 中同时旋转、缩放和平移矩阵?

使用 lapack 计算倒数条件数(即 rcond(x))

fortran90 - Fortran90 中的动态数组分配

c++ - 机器精度问题计算随机正交矩阵