创建可以接受标量或数组的 Fortran 函数
Create fortran function that can accept a scalar or an array
我正在尝试用 fortran 编写一个函数,它接受两个参数,其中一个肯定是一维数组,但另一个参数可以是数组或标量。这类似于可以使用 MIN
或 MAX
内部 fortran 函数执行的操作,这些函数可以比较两个数组,或者一个标量和一个数组(MIN
或 MAX
可以包含更多参数,但我只需要两个)。我一直在网上四处寻找,但令人惊讶的是我还没有找到任何类似的东西。在 Fortran 中可以这样做吗?如果我尝试用 dimension(:)
声明传入参数,编译器只希望它们都是一维数组,并且在标量参数的情况下会抱怨。
你可以通过编写一个封装了这两个函数的通用接口来实现你想要的。这是一个例子
module foo
implicit none ! Never write a module without this statement
private ! Never write a module without this statement
public fcn ! Make the generic function fcn public
interface fcn ! Define generic function
module procedure bar
module procedure bah
end interface fcn
contains
! Function accepts an array and a scalar
function bar(a,b) result(res)
integer res
integer, intent(in) :: a(:)
integer, intent(in) :: b
res = sum(a * b)
end function bar
! Function accepts to arrays
function bah(a,b) result(res)
integer res
integer, intent(in) :: a(:)
integer, intent(in) :: b(:)
res = sum(a * b)
end function bah
end module foo
program testing
use foo
implicit none
integer i(4), j(4), k
i = [1, 2, 3, 4]
j = [10, 20, 30, 40]
k = 10
print *, fcn(i,k)
print *, fcn(i,j)
end program testing
我正在尝试用 fortran 编写一个函数,它接受两个参数,其中一个肯定是一维数组,但另一个参数可以是数组或标量。这类似于可以使用 MIN
或 MAX
内部 fortran 函数执行的操作,这些函数可以比较两个数组,或者一个标量和一个数组(MIN
或 MAX
可以包含更多参数,但我只需要两个)。我一直在网上四处寻找,但令人惊讶的是我还没有找到任何类似的东西。在 Fortran 中可以这样做吗?如果我尝试用 dimension(:)
声明传入参数,编译器只希望它们都是一维数组,并且在标量参数的情况下会抱怨。
你可以通过编写一个封装了这两个函数的通用接口来实现你想要的。这是一个例子
module foo
implicit none ! Never write a module without this statement
private ! Never write a module without this statement
public fcn ! Make the generic function fcn public
interface fcn ! Define generic function
module procedure bar
module procedure bah
end interface fcn
contains
! Function accepts an array and a scalar
function bar(a,b) result(res)
integer res
integer, intent(in) :: a(:)
integer, intent(in) :: b
res = sum(a * b)
end function bar
! Function accepts to arrays
function bah(a,b) result(res)
integer res
integer, intent(in) :: a(:)
integer, intent(in) :: b(:)
res = sum(a * b)
end function bah
end module foo
program testing
use foo
implicit none
integer i(4), j(4), k
i = [1, 2, 3, 4]
j = [10, 20, 30, 40]
k = 10
print *, fcn(i,k)
print *, fcn(i,j)
end program testing