2 回答

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個贊
您不能直接使用Fortran中的函數(shù)來做類似的技巧。您也無法在Fortran中返回閉包。只是寫一個包裝。
function wrap_f(x) result(res)
...
res = f(a,b,...)
end function
它可以是內(nèi)部函數(shù)或模塊函數(shù),并可以通過主機(jī)關(guān)聯(lián)獲取a和b,也可以使用包含a和的模塊b。
如果要將函數(shù)作為實(shí)際參數(shù)傳遞,則在Fortran 2003之前的版本中,它不能是內(nèi)部過程,而只能在Fortran 2008中。它只能在gfortran和ifort的最新版本中使用。為了更好的可移植性,請使用模塊。

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個贊
我可以為這個問題顯示一個很好的解決方案。我也是MATLAB的前用戶,切換到FORTRAN時會錯過函數(shù)句柄哈哈。我以這種方式解決了您的問題:
module
private
public :: f , g
real(kind=RP) :: a0,b0,c0,...
contains
function f(x,a,b,c,d,...)
implicit none
real(kind=RP) :: x,a,b,c,d,...
real(kind=RP) :: f
! Here you define your function
f = ...
end function f
function g(x)
implicit none
real(kind=RP) :: x , g
! Here you call "f" function with the frozen variables *0
g = f(x,a0,b0,c0,...)
end function g
! We said that parameters were private
! (to avoid to be modified from the outside, which can be dangerous,
! so we define functions to set their values
subroutine setValues(a,b,c,...)
implicit none
real(kind=RP) :: a,b,c,...
a0 = a
b0 = b
c0 = c
end subroutine setValues
end module
- 2 回答
- 0 關(guān)注
- 804 瀏覽
添加回答
舉報