本文介绍了在 fortran 中更改数组维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Fortran 90/95 中,基本上有两种方法可以将数组传递给子例程:

There are basically two ways to pass arrays to a subroutine in Fortran 90/95:

PROGRAM ARRAY
INTEGER, ALLOCATABLE :: A(:,:)
INTEGER :: N
ALLOCATE(A(N,N))
CALL ARRAY_EXPLICIT(A,N)
! or
CALL ARRAY_ASSUMED(A)
END PROGRAM ARRAY

SUBROUTINE ARRAY_EXPLICIT(A,N)
INTEGER :: N
INTEGER :: A(N,N)
! bla bla
END SUBROUTINE ARRAY_EXPLICIT

SUBROUTINE ARRAY_ASSUMED(A)
INTEGER, ALLOCATABLE :: A(:,:)
N=SIZE(A,1)
! bla bla
END SUBROUTINE ARRAY_ASSUMED

第二个需要显式接口,通常通过使用模块.

where you need an explicit interface for the second, usually through the use of a module.

从 FORTRAN77 开始,我习惯了第一种选择,我读到如果你传递整个数组,这也是最有效的.

From FORTRAN77, I'm used to the first alternative, and I read this is also the most efficient if you pass the whole array.

显式形状的好处是我还可以调用子例程并将数组视为向量而不是矩阵:

The nice thing with the explicit shape is that I can also call a subroutine and treat the array as a vector instead of a matrix:

SUBROUTINE ARRAY_EXPLICIT(A,N)
INTEGER :: N
INTEGER :: A(N**2)
! bla bla
END SUBROUTINE ARRAY_EXPLICIT

我想知道是否有一种很好的方法可以使用第二个假定形状的界面来完成这种事情,而无需复制它.

I wondered if there is a nice way to do that kind of thing using the second, assumed shape interface, without copying it.

推荐答案

查看 RESHAPE 内在函数,例如

See the RESHAPE intrinsic, e.g.

http://gcc.gnu.org/onlinedocs/gfortran/RESHAPE.html

或者,如果您想避免复制(在某些情况下,优化编译器可能能够在不复制的情况下进行整形,例如,如果 RHS 数组之后不使用,但我不会指望它),如在 Fortran 2003 中,您可以使用 bounds remapping 将指针分配给不同等级的目标.例如.像

Alternatively, if you want to avoid the copy (in some cases an optimizing compiler might be able to do a reshape without copying, e.g. if the RHS array is not used afterwards, but I wouldn't count on it), as of Fortran 2003 you can assign pointers to targets of different rank, using bounds remapping. E.g. something like

program ptrtest
  real, pointer :: a(:)
  real, pointer :: b(:,:)
  integer :: n = 10
  allocate(a(n**2))
  a = 42
  b (1:n, 1:n) => a
end program ptrtest

这篇关于在 fortran 中更改数组维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:33