[英]Calling a Matlab function in Fortran
使用MATLAB 引擎 API 為 Fortran ,我試圖從 Z843E3526BF7A5DFEFE86Z 代碼調用一個簡單的 MATLAB 函數。
我按照此處找到的 fengdemo 示例進行操作。 它起作用了,所以我想調整我的 Fortran 代碼來調用我編寫的特定 Matlab 腳本。
我的 MATLAB 腳本call_fortran.m
非常簡單:它將x
作為條目並將其乘以2
:
function multiply = call_fortran(x)
multiply = 2*x;
end
I want my FORTRAN code to generate a variable my_x
, open a MATLAB session, send the variable to the workspace, apply the function call_fortran
and display the result. 使用 fengdemo.f 代碼,我寫道:
program main
C Declarations
implicit none
mwPointer engOpen, engGetVariable, mxCreateDoubleMatrix
mwPointer mxGetPr
mwPointer ep, my_x ! ep: variable linked to engOpen, starting a Matlab session, my_x: variable que je veux donner a Matlab
double precision my_x
integer engPutVariable, engEvalString, engClose
integer temp, status
mwSize i
my_x = 6
ep = engOpen('matlab ')
if (ep .eq. 0) then
write(6,*) 'Can''t start MATLAB engine'
stop
endif
C Place the variable my_x into the MATLAB workspace
status = engPutVariable(ep, 'my_x', my_x)
C
if (status .ne. 0) then
write(6,*) 'engPutVariable failed'
stop
endif
! My issue now is to call the correct Matlab script
! nlhs = 1
! plhs = 1
! nrhs = 1
! prhs = 1
! integer*4 mexCallMATLAB(nlhs, plhs, nrhs, prhs, functionName)
所以我有我的my_x
,我將它發送到 MATLAB,但是如何應用call_fortran.m
function 並獲得my_x
的新值?
這段代碼有兩個基本錯誤。 您沒有為 my_x 使用正確的變量類型,並且您無法從引擎應用程序(只能在 mex 例程中使用)調用 mexCallMATLAB( )。 讓我們解決這些問題。 首先,my_x 變量需要是 mxArray,而不是雙精度變量。 有多種方法可以做到這一點,但對於標量,創建此數組的最簡單方法如下:
mwPointer, external :: mxCreateDoubleScalar
mwPointer my_x
my_x = mxCreateDoubleScalar(6.d0)
然后,您可以根據當前代碼將其傳遞給 MATLAB 引擎。 要在 MATLAB 引擎工作區中調用您的 function,您需要在此處評估一個字符串:
integer*4, external :: engEvalString
status = engEvalString( ep, 'result = call_fortran(my_x)' )
結果應該顯示在引擎工作區中,因為我們沒有用分號終止字符串。 如果要將結果返回到 Fortran 代碼中,則需要執行以下操作:
mwPointer, external :: engGetVariable
mwPointer result
result = engGetVariable( ep, 'result' )
Fortran 代碼中的結果將是一個 mxArray。 要提取數字有多種方法,但對於標量,最簡單的方法是執行以下操作(使用 real*8 而不是雙精度來完全匹配文檔中的 MATLAB API 簽名):
real*8, external :: mxGetScalar
real*8 myresult
myresult = mxGetScalar(result)
為了避免 memory 泄漏,一旦你完成了 mxArray 變量,你應該銷毀它們。 例如,
call mxDestroyArray(my_x)
call mxDestroyArray(result)
寫完所有這些,您確定要創建 MATLAB 引擎應用程序,而不是 mex 例程嗎? Mex 例程通常更易於使用,並且不需要額外的數據副本來來回傳遞變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.