MATLAB Call C program

Source: Internet
Author: User

MATLAB is a matrix language, if the operation can be implemented by matrix, its operation speed is very fast. But if the computation involves a lot of loops, the speed of MATLAB is unbearable. When the For loop must be used and the corresponding matrix operation is not found to be equivalent, the time-consuming function can be implemented in C and compiled into a MEX file, and MATLAB can invoke a function written in c like a built-in function. Mex file is actually a dynamic link library, the old version of Matlab can directly call the. dll, the new version to invoke the. mexw32 or. mexw64 file.

The compilation process requires the C language compiler, which is installed and configured in MATLAB by typing mex–setup.

the source code of the Mex file consists of :

(1) Function sub-program. This procedure contains the code of the Mex file implementation calculation function, is the standard C language subroutine.

(2) into the incision procedure. This procedure provides the interface between the function subroutine and MATLAB, which is implemented by the Mexfunction function. Note that the name of the ingress process must be mexfunction and contains four parameters, i.e.

void mexfunction (int nlhs,mxarray*plhs[],int nrhs,const Mxarray *prhs[]);

NRHS (left hand side): number of input parameters;

PRHS is an input array whose content is a pointer to a mxarray type of data (all data in MATLAB is Mxarray saved in the form of a matrix).

NLHS, plhs meaning similar.

Specifically, if you execute [a,b]=test (c,d,e) in Matlab, then nlhs=2, Nrhs=3,prhs[0] point to c,prhs[1] point to d,prhs[2] point to E (can be understood as: Prhs[0]=&c, prhs[1]= &d, prhs[2]=&e), note that PRHS is a const pointer array, so it cannot be changed to its point of contents, and the contents of plhs[0],plhs[1] are assigned to a A, B (which can be interpreted as a=*plhs[0]) when the function returns.

Example : New ADD.C, the source code is as follows:

#include "mex.h"  double Add (double x, double y) {    return x + y;} void mexfunction (int nlhs,mxarray *plhs[], int nrh S,const Mxarray *prhs[]) {    double *a;    Double b, C;    Plhs[0] = Mxcreatedoublematrix (1, 1, mxreal);    A = MXGETPR (Plhs[0]);    b = * (MXGETPR (prhs[0]));    c = * (MXGETPR (prhs[1]));    *a = Add (b, c);}

Copy the ADD.C to the current directory in MATLAB, execute the MEX ADD.C, and generate the ADD.MEXW64, which implements the SUM function. You can call the function in MATLAB at this point:

>> output = Add (1.1, 2.2);

Analysis:

#include "mex.h"

The MEX source file must contain mex.h, which provides a large number of interface functions between MATLAB and the C (or Fortran) language, the function prefixes are mex-and mx-two, and the mx-prefixes are mostly functions that operate on mxarray data, such as Mxisdouble, Mxcreatedoublematrix, and mex-prefixes are mostly functions that interact with the MATLAB environment, such as Mexprintf,mexerrmsgtxt. Refer to Apiref.pdf for details.

Plhs[0] = Mxcreatedoublematrix (1, 1,mxreal);

Create a 1x1 double type matrix, return the address of the newly created Mxarray, assign to Pointer plhs[0];

A = MXGETPR (Plhs[0]);

Returns the address of the first real number of the matrix that the pointer plhs[0] points to, and assigns A;

b = * (MXGETPR (prhs[0]));

Get pointer prhs[0] point to the first real number of the matrix and assign to B;

*a = Add (b, c);

Call C program Add, calculate the sum of B,c and assign to the content of a point;

Example: new MYHILB.C, the source code is as follows:

#include "mex.h" void Myhilb (double *y,int n) {    int i,j;    for (i=0;i<n;i++) for        (j=0;j<n;j++)            * (y+j+i*n) =1/(double) i+ (double) j+1);} void mexfunction (int nlhs,mxarray *plhs[],int nrhs,const mxarray *prhs[]) {    double x,*y;       if (nrhs!=1)        mexerrmsgtxt ("one inputs required.");    if (!mxisdouble (prhs[0)) | | MXGETN (Prhs[0]) *mxgetm (prhs[0])!=1)        mexerrmsgtxt ("Input must be scalars.");    X=mxgetscalar (Prhs[0]);    Plhs[0]=mxcreatedoublematrix (x,x,mxreal);    Y=MXGETPR (Plhs[0]);    Myhilb (y, (int) x);}

Copy the MYHILB.C to the current directory in MATLAB, execute the MEX MYHILB.C, generate the MYHILB.MEXW64, which implements the function of calculating the Hilbert matrix (Hilbert matrix: H (i,j) =1/(i+j-1)).

You can call the function in MATLAB at this point:

>> output = MYHILB (6);

Analysis:

A parameter check is performed in Mexfunction, and the function mexerrmsgtxt back to MATLAB when the error message is displayed.

Mxgetscalar: Gets the real part of the first element of the input matrix; Mxgetm: Gets the number of rows of the matrix.

To test the speed difference between the Mex file and the M file, write the M file and run it:

Ticm=10000;a=zeros (m,m); for i=1:m for     j=1:m         A (i,j) =1/(i+j);     Endendtoc

Results: Elapsed time is3.620924 seconds.

Then run the Mex file

Ticoutput = MYHL (10000); TOC

Results: Elapsed timeis 0.730596 seconds.

You can see that the Mex file differs greatly from the M file speed.

VS2010 Generate Mex file (I 64-bit OS)

Using MATLAB to build a Mex file, you can also use VS2010 to generate a Mex file, but you need to configure the VS environment as follows:

1, create a new Win32 Console DLL empty project "MYHILB";

2, the new source file Myhilb.c, the above MYHILB.C content can be copied into;

3. Add a. def file with the content:

LIBRARY

Exportsmexfunction

4. Configure project properties to open the Project Properties Configuration page:

(1) C/c++-> general, additional include directory, input matlab under the installation directory \extern\include

I input E:\Matlab2010\Install\extern\include

(2) linker, general and additional library directory, input matlab under the installation directory \extern\lib\win64\microsoft

I input E:\Matlab2010\Install\extern\lib\win64\microsoft

(3) Additional dependencies, input, connector, input

Libmx.lib

Libeng.lib

Libmat.lib

Libmex.lib

(4) linker-and general-output file, enter $ (OutDir) $ (TargetName). MEXW64 (if not changed here, you can change the suffix name to Mexw64 after generating the DLL file, which also verifies that the MEX is actually a DLL, Just a different suffix)

(5) Target computer, high-level linker, set to MACHINEX64 (32-bit system does not change)

To set the Click App, the 64-bit system that executed the (5) also needs to be executed:

Build, Configuration Manager, active solution platform, change to x64

5, according to F7 compiling project, will be generated under the Debug. mexw64 files, such as:


VS in single-Step Debug Mex file

In the MATLAB environment using the mex–g MYHILB.C command for debugging, but can not add breakpoints for single-step debugging, it is necessary to go to the VS environment debugging.

Whether using vs or using MATLAB to generate MEX files, as long as you have C source files and Mex files you can use VS to the Mex source program plus breakpoints for single-step debugging (we use the above MYHILB.C and MYHILB.MEXW64 test).

1. Change the current directory of MATLAB to the directory where the Mex file (c file) is located;

2. Open c file in VS2010, debug, attach to process, add MATLAB.exe;

3, vs in the C source code to add breakpoints, in the MATLAB command window to invoke the Mex file provided interface;

such as Matlab execution: OUT=MYHILB (6);



At this point, you can press F10 for single-step debugging in VS2010:


To illustrate, in the debugging phase Matlab is in suspended animation state, in addition, MATLAB calls the Mex file after the need to execute the clear all command to delete the Mex file;

Similarly, if you change the current directory of MATLAB directly to the debug directory after using VS to generate a Mex file, you must execute the clear all command to recompile the project after debugging.

Reference:

Http://blog.sina.com.cn/s/blog_468651400100coas.html

Http://www.cppblog.com/xiaozhixd/articles/108490.html

Http://www.linuxidc.com/Linux/2012-08/68148.htm

Http://blog.sina.com.cn/s/blog_a7e72e940101cti9.html

http://blog.csdn.net/raodotcong/article/details/6317273


MATLAB Call C program

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.