[英]Do loop inside a where block in Fortran
盡管我不完全知道為什么,但似乎 Fortran (90) 不允許在where
塊內do
循環。 如下結構的代碼不能用gfortran
編譯( Unexpected DO statement in WHERE block at (1)
):
real :: a(30), b(30,10,5)
integer :: i, j
do i=1,10
where(a(:) > 0.)
! do lots of calculations
! modify a
do j=1,5
b(:,i,j)=...
enddo
endwhere
enddo
我能想到的唯一解決方法是
real :: a2(30)
do i=1,10
a2(:)=a(:)
where(a(:) > 0.)
! do lots of calculations
! modify a
endwhere
do j=1,5
where(a2(:) > 0.)
b(:,i,j)=...
endwhere
enddo
enddo
我想有更優雅的解決方案? 特別是如果where
條件不那么簡單,這很快就會看起來很亂......謝謝!
如果您的 arrays 都是 1-indexed,您可以通過顯式存儲和使用數組掩碼來替換where
構造,例如
program test
implicit none
real :: a(30), b(30,10,5)
integer :: i, j
integer, allocatable :: mask(:)
do i=1,10
mask = filter(a(:)>0.)
! do lots of calculations
! modify a
do j=1,5
b(mask,i,j)=...
enddo
enddo
contains
! Returns the array of indices `i` for which `input(i)` is `true`.
function filter(input) result(output)
logical, intent(in) :: input(:)
integer, allocatable :: output(:)
integer :: i
output = pack([(i,i=1,size(input))], mask=input)
end function
end program
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.