A few points needing attention in MATLAB and C + + mixed MEX programming

Source: Internet
Author: User

Recently do a machine learning topic, the main body is written in Matlab, some of the core algorithm of training is written in C + +, because there are too many loops and numerical calculation in C + + faster. This is my first time in C + + to write Matlab module, feel a lot of detours, the following to share a little experience.

C + + programming in MATLAB is called MEX programming: MATLAB executive MATLAB executable file, as for the specific mechanism of which I am not very clear, some great God will be more aware of the various files generated during the compilation.

1) Indicators and indexes in MEX programming:

The default data type in MATLAB is double, and you can see the data type of the variable using the class () function:

The MATLAB code is as follows:

' - G '  = [1.1,2.1,3;  4,5,6; 7,8,9]mex (a)

The command Mex is used to compile the Mex file, the above code in the Mex mex.cpp '-G ' compiled mex.cpp this C + + file, after the completion of the compilation will generate a "mex.mexw64" file, the suffix name indicates that this is the Win64 under the completion of the Mex file, the back of the '-G ' is an additional parameter that is not to be understood here. The compiled MEX file can be used as a MATLAB function.

The C file mex.cpp code in the same directory as the MATLAB code file is as follows:

 void  mexfunction (int  NLHS, Mxarray *plhs[], int  nrhs, const  Mxarray *prhs[] { double  *input;    Input  = MXGETPR (Prhs[0     first value%f\n   ", *input); printf (   second value%f\n   ", * (Input+1   

Mexfunction has four parameters, NLHS (number left hand s): The numbers of parameters, that is, the MATLAB function output is worth the number, Mxarray *plhs[] is an array of pointers, each element in the array is a pointer to the matrix of the output NRHS is the number of arguments on the right, that is, the number of input parameters, and each pointer in the Mxarray *prhs[] array points to the input matrix. The MXGETPR () function returns a double* pointer to the first element of the matrix, called in the MATLAB Code: MEX (a), that is, prhs[0] is the address of the input matrix A, and input = MXGETPR (Prhs[0]), Input points to the first element of a 1.
What is the address of the second column in the first row of the matrix? Is it (input+1)? Here we run the above MATLAB code, the results are as follows:

As you can see, the output of * (Input+1) is 4, meaning that the MATLAB matrix in C + + is indexed by column. Here is a place to pay attention, because many places to the MATLAB input matrix to traverse to get the matrix element value, if the index error, it is completely wrong. The intrinsic reason for this is that the matrix is indexed by column in Matlab, while in C + + The pointer is added to the line.

There are many functions that allow us to index The matrix, UInt32 Mxgetm (Mxarray *) input a pointer to a matrix, return the number of rows of the matrix, UInt32 mxgetn (Mxarray *) return the number of columns, the number of rows and the number of columns appropriate calculation, you can easily access the matrix element , for example, access a (I,J): * (input+n* (j-1) + (i-1)), N is the number of matrix rows, where 1 is required because the number of line numbers in MATLAB is counted from 1, and the array of C starts with 0.

2) The important relationship between data types and pointer shifts in MEX programming, MXGETPR () and Mxgetdata ():

As I said earlier, the default data type in MATLAB is double, so what happens if you convert the data type of the input matrix of the MEX function?

Matlab code:

1 CLC 2 ' - G ' ; 3 A = [1.1,2.1,3;  4,5,6; 7,8,9]; 4 a= single(a)5 Mex (a)

C + + code:

1#include"mex.h"2 voidMexfunction (intNLHS, Mxarray *plhs[],intNRHS,ConstMxarray *prhs[])3 {4     Double*input;5input = MXGETPR (prhs[0]);6printf"The first value of%f\n",*input);7printf"A second value%f\n", * (input+1));8}

C + + code does not change, MATLAB code is only a data type conversion, we look at the output:

You can see that the output here is not the value we expected. When I debug the MEX code this problem has plagued me for a long time, because Mex inconvenient debugging, many times the output is not desired, and my input matrix are tens of thousands of dimensions, it is difficult to debug. Here the input matrix A becomes a single precision type, as we said earlier, MXGETPR () returns a double pointer, when we use a double type pointer to a single precision (in C + +) We call float float data, of course, will be sent to memory out of bounds, Using a value symbol * to fetch a value exceeds the memory block of the data, so an error occurs if we modify the C + + code:

1#include"mex.h"2 voidMexfunction (intNLHS, Mxarray *plhs[],intNRHS,ConstMxarray *prhs[])3 {4     float*input;5Input = (float*) MXGETPR (prhs[0]);6printf"The first value of%f\n",*input);7printf"A second value%f\n", * (input+1));8}

Set the input type to float and cast the return type of MXGETPR () to float*. Here also a function mxgetdata () can also return the header address of the input matrix, except that Mxgetdata () returns a pointer of type char*, and MXGETPR () returns a pointer of type double*, which can be selected according to its own needs. Or convert the pointer type. If the pointer is of the wrong type, it is very likely to cause a memory access error, which causes Matlab to die.

3) The role of NLHS and NRHS

mexfunction function, two pointer parameters to the input and output of the matrix, and NRHS and NLHS record the number of input and output matrices, in general operation, we only input matrix values, operations, the output matrix assignment, NRHS and NLHS is not very common, But it's also extremely important. For example, in the code above, if I call Mex:mex () in MATLAB code so that no parameters are entered, Matlab will immediately die. Because in the CPP code of the Mex file, you access the value of the input matrix with a pointer, and in the parameter you do not give the MEX input any parameters, so that the matrix pointer is a wild pointer, causing memory errors. If this parameter is wrong in the code, it will cause Matlab to die frequently, my work is very much data, the preparation of data takes a few 10 minutes, which makes me very painful. The solution is to take advantage of the two parameters nlhs and NRHS. Judge the value of NLHS in Mexfunction to determine the number of input parameters, and use NRHS to determine the number of input parameters. If the input parameter is less than a certain value or does not meet your requirements, you can let mexfunction return directly to avoid subsequent programs causing memory errors.


A few points needing attention in MATLAB and C + + mixed MEX programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.