在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的根。
在Matlab中,我可以用一个变量a构建一个新的函数g,参数为b,
g = @(a)f(a,b);
其中b是一个参数,可以在主程序中更改,也可以在f中有作用域。 p>
如何在Fortran 90或95中执行此操作?
解决方案 可以如下处理,尽管它不完全等同于matlab的函数句柄(函数不是Fortran中的一等公民)。
< pre-class =lang-none prettyprint-override> 模块根目录
隐含无
包含
子程序root_finder(f,b)
过程(func):: f
真实,意图(in):: b
抽象接口
实函数func(a,b)
(in):: a,b
结束函数
结束接口
print *,g(2。)
包含
实函数g(a)
实数,意图(in):: a
g = f(a,b)
结束函数
结束子程序
结束模块
正如您所看到的,两个变量的函数以及参数 b
被传递给子例程。该子程序使用内部函数 g(a)
来评估 f(a,b)
。这个函数就像是句柄一样。
一个定义实际函数的例子程序 f(a,b)= a ** 2 + b
:
程序示例
使用根
隐式无
调用root_finder(f,10)
包含
实函数f(a,b)
实数,意图(in):: a,b
f = a ** 2 + b
结束功能
结束程序
输出: 14.0000000
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.
In Matlab, I can build a new function g with only one variable a, with parameter b,
g = @(a) f(a, b);
with b being a parameter that can change in the main program and has scope in f also.
How can I do this in Fortran 90 or 95 ?
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
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".
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
Output: 14.0000000
这篇关于在Fortran 90中,我如何编程matlab中的句柄的等价物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!