如何将变量传递给Fortran IMSL neqnf非线性方程求解器?

时间:2013-05-29 22:45:31

标签: matlab fortran mex nonlinear-optimization imsl

我一直在努力将我的MATLAB程序转换为Fortran(同时仍然利用MATLAB的一些功能)。我正在尝试利用IMSL中可用的例程。它提供了一个非线性方程求解器neqnf,但我无法弄清楚如何根据调用子程序的时间来传递变化的变量(例如,在MATLAB中使用fsolve)。例如,下面是用Fortran编写的调用neqnf的MATLAB函数。子程序sub包含要求解的方程组。如何通过neqnf将变量传递给子,以获得两个线性方程的系数和截距?

谢谢!

#include "fintrf.h"
#include "link_fnl_shared.h"
subroutine mexFunction(nlhs, plhs, nrhs, prhs)
    ! Declarations
    use NEQNF_INT
    implicit none
    external sub

    ! mexFunction arguments
    mwPointer plhs(*), prhs(*)
    integer*4 nlhs, nrhs

    ! mex declarations
    mwpointer mxGetPr,mxCreateNumericArray
    integer*4 mxClassIDFromClassName 

    ! Internal variables
    integer*4 myclassid

    ! Output variables
    mwpointer :: f_pr,x_pr
    double precision :: f(2),x(2)

    ! Create return arguments and assign pointers
    myclassid = mxClassIDFromClassName('double')
    plhs(1) = mxCreateNumericArray(1,2,myclassid,0)
    plhs(2) = mxCreateNumericArray(1,2,myclassid,0)
    f_pr = mxGetPr(plhs(1))
    x_pr = mxGetPr(plhs(2))

    ! Test nonlinear solver (Math.pdf, pg. 1238)
    call d_neqnf(sub,x)

    ! Assign output
    call mxCopyReal8toPtr(f,f_pr,2)
    call mxCopyReal8toPtr(x,x_pr,2)

end subroutine mexFunction

! Subroutine
subroutine sub(x,f,n)
    mwSize n
    double precision :: x(n) ! input
    double precision :: f(n) ! output
    f(1) = 2.d0*x(1) + 1
    f(2) = -1.d0*x(2) + 4
end subroutine sub

1 个答案:

答案 0 :(得分:0)

要将变量放入sub,可以使用模块声明一些变量,然后在sub和主例程中“使用”模块。这样,你可以修改主程序中的变量(或从matlab获取变量),然后在sub中访问它们。

你为什么要转换为fortran?执行速度?

另外,如果您正在进行大量此类转换,请考虑在文件交换中尝试matlab2fmex。它可以为您完成将数值matlab代码转换为fortran的繁忙工作。