在fortran 90中,如何在matlab中编写相当于句柄的程序 [英] In fortran 90, how do I program the equivalent of a handle in matlab
问题描述
我有一个 Fortran90 函数 f(a,b).我需要使用一个一维根查找器,它需要一个函数 g(a),只有一个变量 a,来为 b 的各种值找到 f 的根.
I have a Fortran90 function f(a,b). I need to use a 1D root finder that requires a function g(a), with only one variable a, to find the roots of f for various values of b.
在 Matlab 中,我可以构建一个只有一个变量 a 和参数 b 的新函数 g,
In Matlab, I can build a new function g with only one variable a, with parameter b,
g = @(a) f(a, b);
b 是一个可以在主程序中改变的参数,在 f 中也有作用域.
with b being a parameter that can change in the main program and has scope in f also.
如何在 Fortran 90 或 95 中执行此操作?
How can I do this in Fortran 90 or 95 ?
推荐答案
您可以按如下方式处理这个问题,尽管它并不完全等同于 matlab 的函数句柄(函数在 Fortran 中并不是真正的一等公民).
You can handle this as follows, although it is not fully equivalent to matlab's function handle (functions are not really first-class citizens in Fortran).
module roots
implicit none
contains
subroutine root_finder(f,b)
procedure(func) :: f
real, intent(in) :: b
abstract interface
real function func(a,b)
real, intent(in) :: a,b
end function
end interface
print*, g(2.)
contains
real function g(a)
real, intent(in) :: a
g = f(a,b)
end function
end subroutine
end module
如您所见,两个变量的函数与参数b
一起被传递给子程序.子程序使用内部函数 g(a)
来计算 f(a,b)
.这个函数可以说是句柄".
As you can see, the function of two variables is passed to the subroutine, along with the parameter b
. The subroutine uses an internal function g(a)
to evaluate f(a,b)
. This function is, as it were, the "handle".
一个示例程序,它定义了一个实际的函数f(a,b) = a**2 + b
:
An example program, which defines an actual function f(a,b) = a**2 + b
:
program example
use roots
implicit none
call root_finder(f, 10.)
contains
real function f(a,b)
real,intent(in) :: a,b
f = a**2 + b
end function
end program
输出:14.0000000
这篇关于在fortran 90中,如何在matlab中编写相当于句柄的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!