在Fortran中使用计数器变量而不进行循环

时间:2018-06-27 22:54:06

标签: fortran

我是Fortran的新手,并且对Matlab熟悉,所以我无法将某些逻辑转移到Fortran。我有以下循环:

subroutine B
   use data_structure 
   integer :: i, j, n 
   real :: dt, dxi, dyi 

   allocate(R(n))
   dt = 0.5*CFL*dx**2
   dxi = 1/dx
   dyi = 1/dy
   n = 0

   do j = 1,jmax 
      do i = 1, imax 
         n = n+1 
         R(n) = -rho/dt*((ustar(i+1,j)-ustar(i,j))*dxi+(vstar(i,j+1)-vstar(i,j))*dyi)
         print*, R
      end do 
   end do 
end subroutine B 

您可以看到我正在尝试通过在每次迭代中手动求和n的值来更新向量R。该程序正在运行,但是没有给我预期的结果。有没有更简单的方法可以做到这一点,也许还有另一个do循环?抱歉,编写方法的逻辑使我感到困惑。谢谢!

1 个答案:

答案 0 :(得分:1)

您已经省略了一些关键信息,以了解B所取得的成就。 但是,我估计了模块data_structure和pre_b子例程的最小定义,该子例程列出了可以调用B之前需要的内容。

您还指出了“ n”,R的维是子例程B中的局部整数。需要在调用ALLOCATE ( R(n) )ALLOCATE ( R(imax*jmax) )之前定义它。我将n和k分开作为R(n)的计数器

print*, i,j,R(k)是对如何定义R的更好的临时检查。

module data_structure
!
! these dimensions of arrays need to be provided somewhere
    integer :: imax = 100
    integer :: jmax = 100
!
! these need to be defined before calling B
    real :: CFL
    real :: rho
    real :: dx, dy
!
    real, allocatable :: ustar(:,:)
    real, allocatable :: vstar(:,:)
    real, allocatable :: R(:)

end module data_structure

subroutine pre_B
use data_structure 
!
! somewhere define inputs to subroutine B
!
   imax = 11
   jmax = 11
   allocate ( ustar(imax+1,jmax  ) )
   allocate ( vstar(imax  ,jmax+1) )
!
! get definition of ustar and vstar
   ustar = 1.0
   vstar = 1.0
!   
   cfl = 1.0
   rho = 1.0
   dx  = .01
   dy  = .01
!
! report these values before calling B
!       
end subroutine pre_B

subroutine B
use data_structure 
  integer :: i, j, n, k
  real    :: dt, dxi, dyi 

    n = imax*jmax   !  this is needed ( n is local to subroutine B )
    allocate ( R(n) )

    dt  = 0.5*CFL*dx**2
    dxi = 1/dx
    dyi = 1/dy

    k = 0
    do j = 1,jmax 
        do i = 1, imax 
            k = k+1 
            R(k) = -rho/dt*( (ustar(i+1,j)-ustar(i,j))*dxi    &
                           + (vstar(i,j+1)-vstar(i,j))*dyi )
            print*, i,j,R(k)
        end do 
    end do 

end subroutine B