Matlab calls C program

Source: Internet
Author: User

Matlab calls C program

Matlab is a matrix language. If the algorithm can be implemented using a matrix, the computation speed is very fast. However, if the computation involves a large number of cycles, the speed of Matlab is intolerable. When the for loop must be used and the corresponding matrix operation cannot be found, you can use the C language to implement long-time functions and compile them into the Mex file, matlab can call functions written in C just like calling built-in functions. The Mex file is actually a dynamic link library. The earlier version of Matlab can directly call. dll. The new version needs to call the. mexw32 or. mexw64 file.

The C language compiler is required during compilation. in Matlab, type mex-setup for installation and configuration.

MEX File Source Code Composition:

(1) function subroutine. This process contains the code for implementing the computing function of the Mex file. It is a standard C language subroutine.

(2) entry subroutine. This process provides an interface between the function subroutine and Matlab, which is implemented by the mexFunction. Note that the name of the entry process must be mexFunction and contain four parameters:

Void mexFunction (int nlhs, mxArray * plhs [], int nrhs, const mxArray * prhs []);

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

Prhs is an input array with a pointer pointing to mxArray data (all data in MATLAB is saved in the form of a matrix mxArray ).

Nlhs and plhs have similar meanings.

Specifically, if [a, B] = test (c, d, e) is executed in Matlab, nlhs = 2, nrhs = 3, prhs [0] points to c, prhs [1] points to d, prhs [2] points 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 change its pointing content; when the function returns, plhs [0], the content indicated by plhs [1] is assigned to a and B (it can be understood as a = * plhs [0], B = * plhs [1]).

 

Example: Create 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 nrhs,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 add. c to the current Matlab directory, execute mex add. c, and generate add. mexw64. This file implements the sum function. In this case, you can call this function in Matlab:

> Output = add (1.1, 2.2 );

Analysis:

# Include mex. h

The Mex source file must contain mex. h. The header file provides interface functions between a large number of Matlab and C (or Fortran) languages. The function prefixes are mex-And mx, most functions with mx-prefixes operate on mxArray data, such as mxIsDouble and mxCreateDoubleMatrix. While most functions with mex-prefixes interact with the Matlab environment, such as Mexico,. For more information, see apiref.pdf.

Plhs [0] = mxCreateDoubleMatrix (1, 1, mxREAL );

Create a matrix of the double type of 1x1, return the address of the newly created mxArray, and assign it to the pointer plhs [0];

A = mxGetPr (plhs [0]);

Returns the address of the first real number pointed to by the pointer plhs [0] to the matrix, and assigns it to;

B = * (mxGetPr (prhs [0]);

Obtain the first real number pointing to the matrix from the pointer prhs [0] and assign it to B;

* A = add (B, c );

Call the C program add to calculate the sum of B and c and assign it to the content pointed to by;

Example:Create myhilb. c. The source code is as follows:

# Include mex. hvoid myhilb (double * y, int n) {int I, j; for (I = 0; I
 
  

Set myhilb. copy c to the current Matlab directory and execute mex myhilb. c. Generate myhilb. the file implements the function of calculating the Hilbert matrix (Hilbert matrix: H (I, j) = 1/(I + J-1 )).

In this case, you can call this function in Matlab:

> Output = myhilb (6 );

Analysis:

The parameter check is performed in the mexFunction. The mexErrMsgTxt function returns the error message to MATLAB.

MxGetScalar: Get the real number of the first element of the input matrix; mxGetM: Get the number of rows of the matrix.

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

ticm=10000;a=zeros(m,m);for i=1:m     for j=1:m         a(i,j)=1/(i+j);     endendtoc

Result: Elapsed time is3.620924 seconds.

Run the Mex file.

 

 

ticoutput = myhl(10000);toc

 

Result: Elapsed timeis 0.730596 seconds.

It can be seen that the speed of the Mex file differs greatly from that of the M file.

 

VS2010 generates the Mex File(My 64-bit operating system)

The above uses Matlab to compile and generate the Mex file. You can also use VS2010 to generate the Mex file, but you only need to configure the VS environment. The process is as follows:

1. Create a dll empty project "myhilb" in the win32 console ";

2. Create the source file myhilb. c and copy the above myhilb. c to the file;

3. Add a. def file with the following content:

LIBRARY

EXPORTSmexFunction

4. Configure project properties to open the project properties configuration page:

(1) C/C ++-> General-> Add the inclusion directory and enter externinclude under the installation directory in matlab

Input E: maid

(2) linker-> General-> additional library directory, enter externlibwin64microsoft in the installation directory of matlab

Input E: maid

(3) connector-> input-> additional dependency, input

Libmx. lib

Libeng. lib

Libmat. lib

Libmex. lib

(4) linker-> General-> output file, Input $ (OutDir) $ (TargetName ). mexw64 (if it is not changed here, you can change the suffix name to mexw64 after the dll file is generated. This also verifies that Mex is actually a DLL, but the suffix name is different)

(5) linker-> advanced-> target computer, set to MachineX64 (32-bit system does not need to be changed)

After setting the click application, the 64-bit system that runs (5) still needs to be executed:

Generate-> Configure Manager-> event solution platform, and change to x64

5. compile the project by F7 and generate the. mexw64 file under Debug, for example:

VS single-step debugging of the Mex File

In the Matlab environment, you can use the mex-g myhilb. c command for debugging, but you cannot add a breakpoint for single-step debugging. Therefore, you need to go to the VS environment for debugging.

Whether using VS or Matlab to generate Mex files, as long as there are c source files and Mex files, you can use VS to add breakpoints to the Mex source program for single-step debugging (we use myhilb above. c and myhilb. to perform a test ).

1. Change the current Matlab directory to the directory where the Mex file (C file) is located;

2. Open the C file in VS2010, debug the file-> Add the project and append the field "Matlab. EXE;

3. In VS, add breakpoints to the c source code and call the interfaces provided by the Mex file in the Matlab command window;

Such as Matlab execution: out = myhilb (6 );


 

 

In VS2010, you can perform one-step debugging by pressing F10:

 

 

It should be noted that, in the debugging phase, Matlab is in a false state. In addition, after Matlab calls the Mex file, it must execute the clear all command before deleting the Mex file;

Similarly, if you use VS to generate the Mex file and directly change the current Matlab directory to the Debug directory for debugging, you must execute the clear all command after debugging to re-compile the project.

 

 

Related Article

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.