Mix C and matlab in Linux and mix linuxmatlab

Source: Internet
Author: User

Mix C and matlab in Linux and mix linuxmatlab
1 Overview 1.1 Introduction to Matlab

MATLAB is a commercial mathematical software developed by MathWorks. It is used for algorithm development, data visualization, data analysis, and numerical computing. It is a high-level computing language and interactive environment. It consists of two parts: MATLAB and Simulink. MATLAB is widely used!

MATLAB can also be mixed with other advanced languages such as C/C ++/C #/Java/Fortran.

1.2 What Is A Matlab Engine

The so-called Matlab engine refers to a set of interfaces provided by Matlab. It supports C/C ++, Fortran, and other languages. Through these interfaces, you can control Matlab in other programming environments.



2. Set the 2.1 Matlab Engine dependency condition in the environment before enabling matlab

The matlab Engine depends on/bin/csh, so no matter what shell you use, you must install csh

# Yum install chs (centos/redhat platform)

# Apt-get install chs (ubuntu platform)


2.2 The dynamic library file directory dependent on the matlab Engine must be in the system's current library function search path

You can set the environment

LD_LIBRARY_PATH =/usr/local/matlab/bin/glnx86 (ps: 32)

LD_LIBRARY_PATH =/usr/local/matlab/bin/glnxa64 (ps: 64)

2.3 compile with gcc or g ++


When compiling a program, you must specify the header file directory, the library file directory, and the required library files.

The related commands are as follows:

# Gcc-I/usr/local/matlab/extern/include-o matlab. o matlab. c

# Gcc-L/usr/local/matlab/bin/glnx86-Wl,-rpath,/usr/local/matlab/bin/glnx86-o matlab. o-leng-lmx

2.4 Summary of related environment settings:

The above 2.1 2.2 2.3 describes how to compile C and matlab, but the procedures are complicated. Because we can achieve this through an environment variable setting.

Export PATH = $ PATH: "/usr/local/matlab/bin"

Export LD_LIBRARY_PATH = $ LD_LIBRARY_PATH: "/usr/local/matlab/bin/glnxa64"

Export C_INCLUDE_PATH = $ C_INCLUDE_PATH: "/usr/local/matlab/extern/include"

Export LIBRARY_PATH = $ LIBRARY_PATH: "/usr/local/matlab/bin/glnxa64"


Write the above environment variable settings into the file named xx. env, and then run the command source

# Source xx. env

After the preceding command is executed, all environment variables are set.

Next we can use gcc/g ++ for compilation:

# Gcc test. c-o test-leng-lmex-lmx

Note:/usr/local/matlab/This path is the path when Matlab is installed, which can be changed according to the actual situation.





3 Introduction to Matlab and C interface functions 3.1 startup and shutdown of Matlab Engine

EngOpen-open Matlab engine

Function declaration:

Engine * engOpen (const char * startcmd );

The startcmd parameter is a string parameter used to start the Matlab Engine. It is NULL.

The function return value is an Engine pointer, which is the engine data structure defined in engine. h.


EngClose-Disable the Matlab Engine

Function declaration:

Int engClose (Engine * ep );

The ep parameter indicates the engine pointer to be disabled.

If the return value is 0, the function is disabled successfully. If the return value is 1, an error occurs.


For example, the code used to open/close the Matlab Engine is as follows:


Engine * ep; // defines the Matlab Engine pointer.
If (! (Ep = engOpen (NULL) // test whether the Matlab Engine is successfully started.
Perror ("Can't start Matlab engine! ");
Exit (1 );
EngClose (ep); // disable the Matlab Engine.


3.2 Create and clear mxArray data

Matlab has many types of variables. For each type, there is basically a function for creation, but they all have the same data structure, that is, mxArray.

An array is created using a function in the form of mxCreatexxx. For example, you can create an array of the double type. The available function is mxCreateDoubleMatrix,

Function declaration:

MxArray * mxCreateDoubleMatrix (int m, int n, mxComplexity ComplexFlag );

The m and n parameters are matrix functions and columns. ComplexFlag is a constant used to distinguish whether the elements in the matrix are real numbers or complex numbers. The values are mxREAL and mxCOMPLEX respectively.

For example, to create a two-dimensional real number array with three rows and five columns, you can use the following statement:

MxArray * T = mxCreateDoubleMatrix (3, 5, mxREAL );

To delete an array mxDestroyArray, the function declaration is as follows:

Void mxDestroyArray (mxArray * array_ptr );

The array_ptr parameter is the array pointer to be deleted.


Similar functions include:

Function declaration:

MxArray * mxCreateString (const char * str );

Create a string type and initialize it as a str string.

Generally, in the interaction between C and Matlab, the above two types are enough. The creation of other types of arrays is not described here.

3.3 manage mxArray data types 3.3.1 manage mxArray data size

To obtain the number of elements in each dimension of the mxArray array, you can use the mxGetM and mxGetN functions. MxGetM is used to obtain the number of elements in the first dimension of the array. For a matrix, it is the number of rows.


Int mxGetM (const mxArray * array_ptr); // returns the number of elements in the first dimension of the array corresponding to array_ptr (number of rows)

Int mxGetN (const mxArray * array_ptr); // returns the number of elements in the other dimensions of the array corresponding to array_ptr, which is the number of columns in the matrix. Multi-dimensional arrays are the product of the number of elements in each dimension from the 2nd dimension to the last dimension.

To obtain the number of elements in a specific dimension, use the function:


Const int * mxGetDimensions (const mxArray * array_ptr );

This function returns the number of elements in each dimension of array_ptr stored in an int array. For Commonly Used matrices, you can use mxGetM and mxGetN functions.


In addition, mxGetNumberOfDimensions can be used to obtain the total dimension of the array. mxSetM and mxSetN can be used to set the number of rows and columns of the matrix. The functions are described as follows:


Int mxGetNumberOfDimensions (const mxArray * array_ptr); // returns the dimension of the array.

Void mxSetM (mxArray * array_ptr, int m); // you can specify m as an array.

Void mxSetN (mxArray * array_ptr, int n); // you can specify n as the array.

3.3.2 determine the mxArray type

Before you operate on mxArray variables, you can verify the data type of the arrays in the following table, for example, whether they are double arrays, integers, strings, and logical values, and whether it is a certain structure, class, or special type, such as whether it is an empty array, whether it is inf, NaN, etc. Common judgment functions include:


Bool mxIsDouble (const mxArray * array_ptr );

Bool mxIsComplex (const mxArray * array_ptr );

Bool mxIsChar (const mxArray * array_ptr );

Bool mxIsEmpty (const mxArray * array_ptr );

Bool mxIsInf (double value );

...... ......

These functions are relatively simple and will not be explained.

3.3.3 manage mxArray data

For Commonly Used arrays of the double type, you can use the mxGetPr and mxGetPi functions to obtain the data pointers of the actual and virtual parts respectively. The declaration of these two functions is as follows:


Double * mxGetPr (const mxArray * array_ptr); // returns the Real-Time Pointer of the array array_ptr.

Double * mxGetPi (const mxArray * array_ptr); // returns the virtual pointer of the array array_ptr.

In this way, the data in the mxArray array can be read and written through the obtained pointer. For example, you can use the engGetVariable function to read an mxArray array from the Matlab workspace, and then use mxGetPr and mxGetPi to obtain the data pointer and process the data in it, finally, call the engPutVariable function to re-write the modified array to the Matlab workspace.

3.4 Display/hide the main Matlab window when calling the engine

By default, the main Matlab window is opened when Matlab is called in the engine mode, where you can operate it at will. However, it may also interfere with the running of the application. You can use the following settings to check whether the window is displayed.

Function declaration:

Int engSetVisible (Engine * ep, bool value );

The ep parameter is the opened Matlab Engine pointer, and the value is the identifier of whether to display. The value true (OR 1) indicates that the Matlab window is displayed, and the value false (or 0) indicates that the Matlab window is hidden.

If the return value is 0, the setting is successful. If the return value is 1, an error occurs.

To obtain the display/hide information of the current Matlab window, you can call the function:

Function declaration:

Int engGetVisible (Engine * ep, bool * value );

The ep parameter is the opened Matlab Engine pointer, and the Value is the variable used to save the display/hide situation (transmitted using the pointer method ).

If the return value of the function is 0, the result is obtained successfully. If the return value is 1, an error occurs.

3.5 read and write Matlab data 3.5.1 get variables from the Matlab Engine Workspace

Function declaration:

MxArray * engGetVariable (Engine * ep, const char * name );

The ep parameter is the opened Matlab Engine pointer, And the name is the array name specified in the string form.

The function returns a pointer to the name array.

3.5.2 write variables to the Matlab Engine Workspace

Function declaration:

Int engPutVariable (Engine * ep, const char * name, const mxArray * mp );

The ep parameter is the open Matlab Engine pointer, the mp is the pointer to the written variable, and the name is the variable name written into the Matlab Engine workspace.

If the return value is 0, the variable is successfully written. If the return value is 1, an error occurs.


3.6 send command strings to Matlab

EngEvalString-send command for Matlab to execute.

Function declaration:

Int engEvalString (Engine * ep, Const char * string );

The ep parameter is the engine pointer returned by the engOpen function, and the string is the command to be executed by matlab.

If the return value is 0, the execution is successful. If the return value is 1, the execution fails (for example, the command cannot be correctly interpreted by Matlab or the Matlab Engine has been disabled ).

3.7 obtain the output of the Matlab command window

You can call the engOUtputBuffer function to obtain the output of the command string sent by the engEvalString function in the Matlab window after it is executed by matlab.

Function declaration:

Int engOutputBuffer (Engine * ep, char * p, int n );

The ep parameter is the Matlab Engine pointer, p is the buffer used to save the output structure, and n is the maximum number of characters stored, usually the size of the buffer p. After the function is executed, the command line output result caused by the subsequent engEvalString function is saved in buffer p. To stop saving, you only need to call the code: engOutputBuffer (ep, NULL, 0 ).

4 C call the Matlab quadprog function interface Example

/* Author: bangzhu. liDate: 2014/09 Instruction: This software program is only used as an example, not an error exception handling. e-mail: helpylee@126.com */# include <stdio. h> # include <math. h> # include <stdlib. h> # include "engine. h "# include <string. h> int main (int argc, char ** argv) {Engine * ep; if (! (Ep = engOpen ("\ 0") // start the matlab engine {fprintf (stderr, "\ nCan't start MATLAB engine \ n"); return EXIT_FAILURE ;} engSetVisible (ep, false); mxArray * H = NULL, * f = NULL, * A = NULL, * B = NULL, * lb = NULL, * x = NULL; H = mxCreateDoubleMatrix (2, 2, mxREAL); f = mxCreateDoubleMatrix (2, 1, mxREAL); A = mxCreateDoubleMatrix (3, 2, mxREAL); B = mxCreateDoubleMatrix (3, 1, mxREAL); lb = mxCreateDoubleMatrix (2, 1, mxREAL); x = mxCreateDoubleMatrix (2, 1, mxREAL); double HH [2] [2] = {1,-1, -}; double ff [2] [1] = {-2,-6}; double AA [3] [2] = }; double bb [3] [1] = {2, 2, 3}; double llbb [2] [1] = {0, 0 }; double xx [2] [1] = {0, 0}; // converts the C array to the Matlab array memcpy (void *) mxGetPr (H), (void *) HH, sizeof (double) * 2*2); memcpy (void *) mxGetPr (f), (void *) ff, sizeof (double) * 2*1 ); memcpy (void *) mxGetPr (A), (void *) AA, sizeof (double) * 3*2); memcpy (void *) mxGetPr (B ), (void *) bb, sizeof (double) * 3*1); memcpy (void *) mxGetPr (lb), (void *) llbb, sizeof (double) * 2*1); memcpy (void *) mxGetPr (x), (void *) xx, sizeof (double) * 2*1 ); // write the array variables to engPutVariable (ep, "H", H); engPutVariable (ep, "f", f); engPutVariable (ep, "", a); engPutVariable (ep, "B", B); engPutVariable (ep, "lb", lb); engPutVariable (ep, "x", x ); // execute the string command int ret1 = engEvalString (ep, "H = [1-1;-1 2];"); int ret2 = engEvalString (ep, "f = [-2;-6];"); int ret3 = engEvalString (ep, "A = [1 1;-1 2; 2 1];"); int ret4 = engEvalString (ep, "B = [2; 2; 3];"); int ret5 = engEvalString (ep, "lb = zeros (2, 1 );"); int ret6 = engEvalString (ep, "[x] = quadprog (H, f, A, B, [], [], lb, [], []);"); char p [256] = {0}; char p1 [256] = {0}; char * ans = "disp (x ));"; char * ans2 = "disp (x (2, 1);"; engOutputBuffer (ep, p, 240); engEvalString (ep, ans); printf ("p: % s \ n ", p); engOutputBuffer (ep, p1, 240); engEvalString (ep, ans2); printf (" p1: % s, \ n ", p1 ); mxDestroyArray (H); mxDestroyArray (f); mxDestroyArray (A); mxDestroyArray (B); mxDestroyArray (x); engClose (ep); return 0 ;}



Can linux c be mixed with matlab?

Yes. There are books mixed with linux c and matlab. You can check them on the internet and check them.
In linux, matlab and c Mixed encoding encounter the following problems:

The gcc version is too high. You can re-apt-get a gcc4.2 and replace the gcc symbolic link.
Mutils. h is missing.

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.