0

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

谢谢!

#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
4

1 回答 1

0

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

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

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

于 2013-05-30T10:47:59.643 回答