1. 程式人生 > >MATLAB 呼叫編譯.c/.cpp檔案

MATLAB 呼叫編譯.c/.cpp檔案

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1、設定編譯器</span>

在命令視窗輸入 mex -setup,根據提示選擇合適的編譯器。通常我們使用的都是“Microsoft Visual C++”編譯器。

如果編譯器設定有問題,具體可以到官網檢視不同MATLAB支援的編譯器型別以及具體的問題。不過,通常都不會有問題。

2、建立編輯.c或者.cpp檔案並編譯

(1)開頭輸入   

#include "mex.h"
(2)編輯自己的函式(注意新增自己所需的標頭檔案,就和平時寫C語言一樣)
/* The computational routine */
/*函式功能:n維向量y乘以一個標量x得到一個n維向量z*/
void arrayProduct(double x, double *y, double *z, mwSize n)
{
    mwSize i;//mwsize類似於int
    /* 把每一個y同x相乘 */
    for (i=0; i
(3)建立程式入口
C專案都有一個main函式作為程式入口,MATLAB呼叫時沒有main函式,因此我們也需要建立一個入口。格式如下:
/* 入口函式 */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
/* 變數宣告*/

/* 程式碼*/
}

引數說明如下圖:
完整的這段程式碼如下:
/* 入口函式 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
    double multiplier;              /* 輸入標量x*/
    double *inMatrix;               /* 輸入1×n的向量y*/
    size_t ncols;                   /* 輸入向量的維度*/
    double *outMatrix;              /* 輸出矩陣 */

    /* 以下檢查函式引數個數是否正確,可以省略*/
    if(nrhs!=2) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nrhs","Two inputs required.");
    }
    if(nlhs!=1) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:nlhs","One output required.");
    }
    /* make sure the first input argument is scalar */
    if( !mxIsDouble(prhs[0]) || 
         mxIsComplex(prhs[0]) ||
         mxGetNumberOfElements(prhs[0])!=1 ) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notScalar","Input multiplier must be a scalar.");
    }
    
    /* make sure the second input argument is type double */
    if( !mxIsDouble(prhs[1]) || 
         mxIsComplex(prhs[1])) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notDouble","Input matrix must be type double.");
    }
    
    /* check that number of rows in second input argument is 1 */
    if(mxGetM(prhs[1])!=1) {
        mexErrMsgIdAndTxt("MyToolbox:arrayProduct:notRowVector","Input must be a row vector.");
    }
    
    /* 獲得x的值 */
    multiplier = mxGetScalar(prhs[0]);

    /* 建立一個指向輸入向量y的指標 */
    inMatrix = mxGetPr(prhs[1]);

    /* 獲得輸入向量y的維度n */
    ncols = mxGetN(prhs[1]);

    /* 建立一個輸出矩陣*/
    plhs[0] = mxCreateDoubleMatrix(1,(mwSize)ncols,mxREAL);

    /* 獲得指向輸出向量z的指標*/
    outMatrix = mxGetPr(plhs[0]);

    /* 呼叫計算程式 */
    arrayProduct(multiplier,inMatrix,outMatrix,(mwSize)ncols);
}
(4)將上述儲存為.c檔案後(注意檔名和函式名要相同),在MATLAB命令視窗輸入下面的指令進行編譯
mex arrayProduct.c
3、呼叫,和普通的MATLAB函式一樣使用。不過需要注意編譯的檔案要位於當前路徑。 例如對上面函式的呼叫: s = 5; 
A = [1.5, 2, 9];
B = arrayProduct(s,A)
B =7.5000   10.0000   45.0000