A Preliminary Study on the Mixed Programming of C/C ++ and Matlab

Source: Internet
Author: User

A Preliminary Study on the Mixed Programming of C/C ++ and Matlab

========================================================== ====================

% You are welcome to repost and respect originality. Therefore, please indicate the source for reprinting.

% Http://blog.csdn.net/bendanban/article/details/37830495

% This article is for the CSDN 2014 blog contest finals. Welcome to vote.

% Click "Vote". After Entering the link, log on (you can use the QQ number) and pull it to the bottom. Click "Vote]

= ====================


Matlab has rich functions and simple programming. However, in some cases, the execution speed of the Matlab program is relatively slow. C/C ++ compilation and execution programs are faster, and programming is more difficult than Matlab. Therefore, there is a solution that uses Matlab to implement our experimental program and C/C ++ to implement the time-consuming part of the Matlab program, call the C/C ++ program from the Matlab program for acceleration.

This article mainly explains how to call C/C ++ programs in Matlab and how to compile C/C ++ programs that can be called by Matlab programs.

This article consists of the following parts:

Hello Matlab, a simple example shows how to call the C/C ++ program in Matlab, And what basic matters should be paid attention to for the C/C ++ program that can be called by Matlab.

Matlab calls the C/C ++ program to pass parameters. This article discusses how to use Matlab parameters in C/C ++.

Description of data storage. Describes how to store data in Matlab.

Note:This article believes that the reader will use Matlab to master the C/C ++ language and has a computer. A Windows operating system is installed on the computer, and Matlab and Visual Studio (such as VS2008 and VS2010) are installed on the operating system ). Or the Linux operating system is installed on the computer, and the system is installed with Matlab and GCC.


Hello Matlab

We complete a program called "Hello Matlab" step by step.

Step 1: create a directory named HiMat under drive D of your computer. Create a text file named "abhimat. cpp" under the D: \ HiMat directory ". Copy the Code in Code 1 to the "abhimat. cpp" file,Save. (Note:Directory Creation, naming, and other behaviors are not specified here, just for convenience ).

#include "mex.h"void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){  mexPrintf("hello matlab in C/CPP.\n");}
Code 1, abhimat. cpp

"Abhimat. cpp" is the C/C ++ code to be called in Matlab.

Step 2: Compile "abhimat. cpp" in Matlab ". Start Matlab, enter the D: \ HiMat directory, execute the command in code 2 in the Matlab command window, and complete the C/C ++ compiling environment configuration as prompted.Note:: If you have multiple compilers, we recommend that you select the latest one.

mex -setup
Code 2: Set the C/C ++ compiling environment of Matlab

After the configuration is complete, run the Code 3 command in Matlab to compile abhimat. cpp.

mex abhimat.cpp
Code 3: Compile abhimat. cpp

Step 3: Execute the compiled C/C ++ program. You can enter "abhimat" or "abhimat ()" in the Matlab command window to call the compiled program. We recommend that you use the latter.

Careful readers have noticed that:

  • The C/C ++ function name called in Matlab is the file name suffixed with mex * (here, * represents any number of characters, for example, mexw64) after compilation.
  • After Matlab executes the abhimat () command, the program in the mexFunction is actually executed.

Matlab calls the C/C ++ program to Transfer Parameters


In this section, we will discuss how we know the type and number of parameters called by Matlab in the C/C ++ program called by Matlab.

An example of calling the C/C ++ program in Matlab is provided, as shown in code 4.

c = [1 2;3 4;5 6];d = [1 1;1 1;1 1];[a, b] = abfunc(c, d);
Code 4, Matlab calls the C/C ++ program instance

The following work is how to implement the mexFunction in the file named abfunc. cpp under the current directory. In this function, how can we obtain the values of c and d variables in the Matlab command, and how can we return the values of a and B variables.

Pay attention to the four parameters in the mexFunction:

Nlhs: the first parameter of Mexico function, which indicates that there are several variables on the left side of the moderate sign in the Matlab call command. For example, for calls in code 4, the value of nlhs is 2, because there are two variables on the left of its equal signs, they are a and B.

Plhs: The second parameter of Mexico function, which indicates the pointer to the left variable of the moderate number in the Matlab call command. For example, for calls in code 4, plhs [0] indicates a, and plhs [1] indicates B.

Nrhs: The third parameter of Mexico function, which indicates the number of variables on the right of the moderate number of Matlab call commands. For example, for calls in code 4, the value of nrhs is 2, because there are two variables on the right of its equal sign, they are c and d.

Prhs: The fourth parameter of Mexico function, which indicates the variable pointer to the right of the Matlab call command medium number. For example, for calls in code 4, prhs [0] indicates c, and prhs [1] indicates d.

MxArrary is an invisible data type defined by Matlab. You only need to know that the mxArrary pointer exactly corresponds to the variables in Matlab.

The following code implements abfunc. cpp with the functions a = c + d and B = c-d, as shown in code 5.

#include "mex.h"void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){  double *p_c, *p_d;  double *p_a, *p_b;  int c_rows, c_cols;  int d_rows, d_cols;    int numEl;  int n;    mxAssert(nlhs==2 && nrhs==2, "Error: number of variables");  c_rows = mxGetM(prhs[0]);// get rows of c  c_cols = mxGetN(prhs[0]);// get cols of c  d_rows = mxGetM(prhs[1]);// get rows of d  d_cols = mxGetN(prhs[1]);// get cols of d  mxAssert(c_rows==d_rows && c_cols==d_cols, "Error: cols and rows");  // create output buffer  plhs[0] = mxCreateDoubleMatrix(c_rows, c_cols, mxREAL);  plhs[1] = mxCreateDoubleMatrix(c_rows, c_cols, mxREAL);  // get buffer pointers  p_a = (double*)mxGetData(plhs[0]);  p_b = (double*)mxGetData(plhs[1]);  p_c = (double*)mxGetData(prhs[0]);  p_d = (double*)mxGetData(prhs[1]);  // compute a = c + d; b = c - d;  numEl = c_rows*c_cols;  for (n = 0; n < numEl; n++)  {    p_a[n] = p_c[n] + p_d[n];    p_b[n] = p_c[n] - p_d[n];  }}
Code 5, abfunc. cpp implementation

Describes the functions used in code 5. Most of these functions start with mx. MxAssert is an assert in C \ C ++. MxGetM obtains the number of rows of variables sent from Matlab, and mxGetN obtains the number of columns of variables sent from Matlab. MxCreateDoubleMatrix creates a two-dimensional Matlab variable, which is used to specify the number of rows, columns, and Element Types of the variable (mxREAL indicates the real number, and mxCOMPLEX indicates the complex number ). MxGetData is used to obtain the first address of the data block in the memory.

Compile and test the Code in Code 5. For details, see Code 6.

mex abfunc.cppc = [1 2;3 4;5 6];d = [1 1;1 1;1 1];[a, b] = abfunc(c, d);
Code 6, Code5 test Code

The output result of Code 6 is as follows:

a =     2     3     4     5     6     7b =     0     1     2     3     4     5



Description of data storage

Data in Matlab is stored by column. For example, if a = [;], the storage sequence of a's data in the memory is: 1, 3, 5, 2, 4, 6. When a variable sent from Matlab is used in C \ C ++,Pay attention to the data storage sequence..


Additional: Code download location: http://download.csdn.net/detail/bendanban/7643701


Matlab and CAI c/c ++ Mixed Programming

Functions in matlab are not all used at will, and some toolbox functions cannot be used directly. It is possible that matlab 6.5 can be used, but the later version of matlab has some problems. In addition, the hybrid programming of matlab and VC should be used in combination with the actual situation, and sometimes the efficiency is not high. Some time ago, I was engaged in the com-Based Mixed Programming of VC and matlab. The neural network toolbox can only be used for matlab 6.5.

Mixed Programming of C language and matlab

Mixed programming through matcom.

First, convert the matlab language to dll, which can be called in c.

Of course, the new version of matlab can directly convert m language into standard c

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.