Matlab中mex與C混合程式設計總結

2021-06-04 12:13:00 字數 2899 閱讀 6484

使用mex和c可以加快演算法的執行速度,mex檔案包含乙個入口函式如下:

void mexfunction( int nlhs, mxarray *plhs,int nrhs, const mxarray *prhs ) 

入口函式有四個引數:prhs為mxarray結構體型別的指標陣列,該陣列的元素按順序指向所有的輸入引數;

nrhs為整數型別,它標明了輸入引數的個數。

plhs:為mxarray結構體型別的指標陣列,該陣列的元素按順序指向所有的輸出引數;

nlhs:輸出引數的個數

在入口程式完成兩件事情:第一:從輸入的mxarray結構體中獲得計算完畢的資料,然後在使用者的子程式中加以使用

第二:使用者可以將計算完畢的結果返回給乙個用於輸出的mxarray結構體。

mex原始檔的兩個組成部分可以分為兩個檔案也可以放在乙個檔案中,必須包含mex.h標頭檔案,該標頭檔案包含matrix.h和一些

以mex開頭的子函式。

下面舉幾個例子:

#include "mex.h"

/* 輸入引數 */

#define minput prhs[0]

/* 輸出引數 */

#define outm plhs[0]

void mexfunction( int nlhs, mxarray *plhs,

int nrhs, const mxarray *prhs )

input= mxgetpr(minput); /*獲取矩陣*/

n = mxgetm( minput ); /*獲取矩陣的行*/

l = mxgetn( minput); /*獲取矩陣的列*/

for( i=0;i

#include "mex.h"

void

mexfunction(int nlhs,mxarray *plhs,int nrhs,const mxarray *prhs)

if (nlhs > 1)

/* check for proper input type */

if (!mxischar(prhs[0]) || (mxgetm(prhs[0]) != 1 ) )

/* find out how long the input string is. allocate enough memory

to hold the converted string. note: matlab stores characters

as 2 byte unicode ( 16 bit ascii) on machines with multi-byte

character sets. you should use mxchar to ensure enough space

is allocated to hold the string */

buflen = mxgetn(prhs[0])*sizeof(mxchar)+1;

buf = mxmalloc(buflen);

/* copy the string data into buf. */

status = mxgetstring(prhs[0], buf, buflen);

mexprintf("the input string is: %s\n", buf);

/* note: you could add your own code here to manipulate

the string */

/* when finished using the string, deallocate it. */

mxfree(buf);

}

動態分配記憶體的例子:

#include "mex.h"

/* the mxarray in this example is 2x2 */

#define rows 2

#define columns 2

#define elements 4

void mexfunction(int nlhs, mxarray *plhs, int nrhs, const mxarray *prhs) ; /* existing data */

mwsize index;

/* check for proper number of arguments. */

if ( nrhs != 0 )

/* create a local array and load data */

dynamicdata = mxmalloc(elements * sizeof(double));

for ( index = 0; index < elements; index++ )

/* create a 2-by-2 mxarray; you will copy existing data into it */

plhs[0] = mxcreatenumericmatrix(rows, columns, mxdouble_class, mxreal);

pointer = mxgetpr(plhs[0]);

/* copy data into the mxarray */

for ( index = 0; index < elements; index++ )

/* you must call mxfree(dynamicdata) on the local data.

this is safe because you copied the data into plhs[0] */

mxfree(dynamicdata);

return;

}

複製搜尋 複製

搜尋 複製搜尋 複製

搜尋

matlab和C C 混合程式設計 Mex

最近的專案需要matlab和c的混合程式設計,經過一番努力終於完成了專案要解決的問題。現在就將mex的一些經驗總結一下,當然只是剛剛開始,以後隨著學習的深入繼續新增。首先講講寫mex的一些常規規定,然後我們會重點關注混合程式設計中最難解決資料的問題 結構到底如何轉換,並且後面會重點說一下自己的程式。...

matlab混合程式設計之mex檔案

1 mex檔案結構 a 子程式 b 入口程式 void mexfunction int nlhs,mxarray plhs,int nrhs,const mxarray prhs 2 語法 include mex.h void timestwo alt double y,double x void ...

Matlab與C 混合MEX程式設計

一 mexfunction 與c中的main函式一樣,mex程式中的開始函式為mexfunction.預設變數引數是 void mexfunction int nlhs,mxarray plhs,int nrhs,const mxarray prhs 其中nlhs指的是在呼叫函式時返回值的個數 pl...