2008-10-15

Matlab 呼叫 C 寫成的 function

因為需要,所以有稍微研究了一下。而且,用C的速度比Matlab快太多了。
大致的流程為:
1、Programming in C
2、Using 「mex」 to compile the file to MEX-files
3、Use the function in Matlab

【設定compiler】
要在 Matlab 中呼叫 C 寫成的 function,首先要先設定 compiler。在 Matlab 下編譯 C/C++ 函式庫的指令為 mex ,但在使用 mex 之前,必須先設定編譯器的種類和參數。
在命令提示字元或者在Matlab下 "mex -setup"來選擇所需要的compiler。
會先問你要不要選擇已經安裝的compiler,接下來在選擇所需的compiler即可。


【撰寫 C/C++ 函式】
寫 C/C++ 程式並不難,一開始的困難點在於與 Matlab 的溝通介面。
Gateway Routine 是 Matlab與 C 的一個溝通介面,也是程式的進入點。Gateway Routine就像

void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
/* more C code ... */
}


要撰寫Gateway Routine要注意下面幾點:
1、Gateway Routine的命名
2、標頭檔
3、所需的參數
4、Mex-file的命名

Gateway Routine的命名
Gateway Routine的名稱必須為mexFunction。

標頭檔
在程式前端加入 #include "mex.h"

所需的參數
nlhs:呼叫函式時,等號左邊的變數數目,即 plhs 之個數。
plhs:呼叫函式時,等號左邊之變數本體。
nrhs:呼叫函式時,等號右邊的變數數目,即 prhs 之個數。
prhs:呼叫函式時,等號右邊之變數本體。
例如在Matlab的function
[M, I] = larger(A, B);
nlhs=nrhs=2
plhs[0] -> M ,plhs[1] -> I
prhs[0] -> A ,prhs[1] -> B

Mex-File 的命名
檔案名稱必須和在Matlab要呼叫的function 一樣。

最後,進行編譯 mex filename.c 或者 mex filename.cpp 就可以了。

[參考資料]
Building MEX-Files
Creating C Language MEX-Files


(繼續閱讀...)