Recent projects require a mix of MATLAB and C programming, and after some effort, the project is finally completed. Now, some of the experience of Mex is summed up, of course, just beginning, and later with the depth of learning continue to add. Let's start with some of the general rules of MEX, and then we'll focus on the most difficult data-solving problem in hybrid programming-how the structure is transformed, and then focus on your program.
I. Structure of the MEX
First look at a simple program (the program is saved in the MATLAB Master directory name is MexDemon.cpp, or in the home directory to create a new. cpp file):
#include "mex.h"//header file, which cannot include in VS2010, but does not affect its compilation in MATLAB, But in MATLAB compiled also need include it # include <vector>using namespace std;void mexfunction (int nlhs, Mxarray *plhs[],int NRHS, Const Mxarray *prhs[])//mexfunction is similar to the main function {//NLHS represents the number of output parameters//PLHS is an array of pointers, the pointer to the Mxarray type, each pointer to an output//NR HS represents the number of input parameters//PRHS is an array of pointers, with pointers pointing to mxarray types, each pointing to an input vector<vector<double> > array2d; Double *z; Plhs[0] = Mxcreatedoublematrix (5, 6, mxreal);//The first output is a 5*6 matrix z = MXGETPR (plhs[0]);//Gets a pointer to the first element of the Matrix Array2d.resize (5 ); int II = 0; for (int i = 0; i < 5; i++) {for (int j = 0; J < 6; J + +) {z[i*6 + j] = II;//pointer access matrix is column-first, please cycle the program and analyze the output The result is ii++; }}}/* *ans = 0 5 10 15 20 25 1 6 11 16 21 26 2 7 12 17 22 3 8 of 4 9 */
Then set the compiler for MATLAB to compile the application Mex, and enter Mex–setup in the command window. Then follow the steps to choose the right compiler.
After the compiler is set up in the Command window, enter Mex mexDemon.cpp to compile and generate the. mexw64 file, which can be called directly after the build, for example, this example can be called directly in the command window to enter a = Mexdemon (); The return value is as above.
Conversion of data structures of the second, C and MATLAB
(1) Transfer of values
MATLAB-C + +
x = Mxgetscalar (prhs[0]);//The function obtains the value that Matlab passes over;
MATLAB, C + +
plhs[0] = Mxcreatedoublematrix (1,1, mxreal); // Create the returned matrix, range plhs[0] to Mxarray type y = mxgetpr (plhs[0]); // gets the data address of the return plhs[0], and can then modify the value of Y to return the
An instance (NumDemon.cpp):
#include "mex.h" void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const Mxarray *prhs[]) { int x = mxgetscalar (prhs [0]); Convert the first input parameter to scalar scalar, i.e. single value printf ("%d\n", x);//print double *y; Plhs[0] = Mxcreatedoublematrix (1,1,mxreal); Let the first output parameter point to a 1*1 matrix y = MXGETPR (plhs[0]);//Get a pointer to the first element of the matrix *y = 10;//Assign it a value of 10}
As in the command Window compile:
(2) incoming and outgoing matrices
About the incoming (Matlab to C + +, is the first example), the following can give an example of how to transfer from C + + to MATLAB, see the following code:
#include "mex.h" void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const Mxarray *prhs[]) { double *datacursor;
vector<vector<double> > parms; Datacursor = MXGETPR (Prhs[0]); Gets the pointer of the first element of the input matrix int mrows = Mxgetm (Prhs[0]); Gets the line int ncols = MXGETN (Prhs[0]) of the matrix; Get the matrix of the columns printf ("%d_%d\n", Mrows, ncols); Print rows and Columns parms.resize (mrows); Initialize for (int i = 0; i < mrows; i++) { parms[i].resize (ncols); } for (int i = 0, i < mrows; i++) {for (int j = 0; J < Ncols; J + +) { Parms[i][j] = datacursor[j * mrows + i]; /Copy the element of the matrix to vector of Vector }}
You can also compile the command window.
(3) Incoming and outgoing string
MATLAB-C + + (incoming)
Char *input_buf;input_buf = mxarraytostring (Prhs[0]);//Use mxarraytostring to convert Mxarray to C, C + + string
C + + matlab (outgoing)
Char *output_buf;//defines the string cache size_t Buflen = (Mxgetm (prhs[0]) * MXGETN (Prhs[0])) + 1;//Gets the string length, Mxgetm gets the number of rows, Mxgetn gets the number of columns Output_buf=mxcalloc (Buflen, sizeof (char));//Use Mxcalloc to assign an array of output strings plhs[0] = mxcreatestring (OUTPUT_BUF);// Create Mxarray output Mxfree (output_buf) using Mxcreatestring;
An instance (strDemon.cpp)
#include "mex.h" void Revord (char *input_buf, size_t Buflen, char *output_buf) { mwsize i; if (Buflen = = 0) return; for (i=0;i<buflen-1;i++) * (output_buf+i) = * (input_buf+buflen-i-2);} void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const Mxarray *prhs[]) { char *input_buf, *output_buf; size_t Buflen; Buflen = (Mxgetm (prhs[0]) * MXGETN (Prhs[0])) + 1; Because this program is flipping strings, the input and output string should be the same length as output_buf=mxcalloc (Buflen, sizeof (char));//Application space Input_buf = Mxarraytostring (Prhs[0]); Get input string Revord (Input_buf, Buflen, output_buf);//Flip string plhs[0] = mxcreatestring (OUTPUT_BUF); Mxfree (INPUT_BUF); return;}
You can also compile it.
(4) The cell's incoming
#include "mex.h" void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const Mxarray *prhs[]) {mwsize Cellndim = Mxgetnumber Ofdimensions (Prhs[0]); Here are two functions mxgetnumberofdimensions and mxgetdimensionsconst int *cellcolptr = mxgetdimensions (Prhs[0]);// Mxgetdimensions: is to return a pointer to PTR, each pointer pointing to the value is the number of elements per dimension. For example, matrices with matrix 3*2, then * (PTR) is 3,* (ptr+1) for 2.//mxgetnumberofdimensions: Returns the dimension of Mxarray. int cellnrow = * (label_dims); int cellncol = * (label_dims + 1); Mxarray *ptr; ptr = Mxgetcell (Prhs[0], 0); Gets the No. 0 element of the cell, returns a Mxarray pointer, and the second parameter represents the subscript Mxarray *cellofcell of the element in the cell ; Cellofcell = Mxgetcell (ptr, 0); Of course the cell inside can or cell, then should be like to write Mxarray *cellofstr; char *chtmp; Cellofstr = Mxgetcell (Prhs[0], 0); Of course the cell inside can be a string chtmp = mxarraytostring (CELLOFSTR); printf ("%s\n", chtmp);}
After the addition of the structure and the cell array to the outgoing, temporarily did not encounter such a requirement. Put a few more reference URLs:
1.http://blog.sina.com.cn/s/blog_9db9f81901013yv2.html
2.http://blog.sina.com.cn/s/blog_80202a090100uhup.html
MATLAB and C/+ + mixed programming--mex