Interfaces between MATLAB and C ++

Source: Internet
Author: User
Tags integer numbers
What is MATLAB? Needless to say, a large number of experts will tell you the numerous benefits of it. However, the common problems in the MATLAB program are:
1. The operation speed is slow, especially for I = 1 :???
For j = 1 :???
......
End
Then you will die.
2. It cannot be run without the MATLAB environment. Although you can use the tool provided by MATLAB to convert M Files into executable programs, you can only see a black window during execution, this is ...... windows? $ % & % ^ $ ##% &.
3. Poor GUI functions. Many heroes do not want to see the DOS-Windows interface described in 2, so they use the GUI generation tool with MATLAB. (Do not throw an egg! I know that you changed the interface with Graphic Editor and found that all the previous work was done in white-because it was covered, West), but the controls and events provided by MATLAB are limited. After the GUI is completed, it is placed in the machine, showing off to the teachers and sisters who are not yet in the lab, and barely adding some charm values. If you see it by experts, Westbrook. I'm afraid the effect is not very good.
Therefore, if MATLAB can interact with visual design languages such as VC, BC, or C ++ BUILDER to improve the speed, beautify the interface, and make programs more in line with Windows specifications, at the same time, it makes sense for anyone to use the powerful functions of MATLAB.
I have covered some of the interfaces between MATLAB and C ++ in this topic. I will summarize them here. Here are some of the errors and their bias. Please give me some advice from heroes and experts. Thank you!
(1) Interface Types
There are three ways to Operate MATLAB in C ++ (or C:
· MEX File
C or Fortran programs that can be called in MATLAB are called MEX files. MATLAB can directly regard the MEX file as its built-in function for calling. A mex file is a child routine of Dynamic Linking. The MATLAB interpreter can automatically load and execute it. MEX files are mainly used for the following purposes:
A large number of existing C or Fortran programs can be executed in MATLAB without being rewritten to the M file format dedicated to MATLAB.
For algorithms that run slowly in MATLAB, they can be written in C or Frotran to improve efficiency.
· MAT file application
The MAT file is a data file format dedicated to MATLAB used to save data to disks and import data to MATLAB and export data from MATLAB. The MAT file provides a simple mechanism that allows you to move data flexibly between two platforms. It also provides a way to import or export data to other single-host MATLAB applications.
To simplify the use of MAT files outside the MATLAB environment, MATLAB provides an Operating Routine Library, through which we can use C/C ++ or Fortran programs to read and write MAT files.
· Engine Applications
MATLAB provides a series of routines so that other programs can call MATLAB and use MATLAB as a computing engine. MATLAB Engine programs refer to C/C ++ or Fortran programs that communicate with independent MATLAB processes through pipelines (in UNIX systems) or ActiveX (in Windows systems.
MATLAB also provides a function library to start or end the MATLAB process, exchange data with MATLAB, and send MATLAB commands.
(2) MEX files
1. An example of MEX
# Include "mex. h"
/*
* Timestwo. c-example found in API guide
*
* Computational function that takes a scalar and doubles it.
*
* This is a MEX-file for MATLAB.
* Copyright (c) 1984-1998 The MathWorks, Inc.
*/
/* $ Revision: 1.5 $ */
/* The purpose of this MEX file is to implement the timestwo function.
Void timestwo (double y [], double x []) is your C ++ function */
Void timestwo (double y [], double x [])
{
Y [0] = 2.0 * x [0];
}

/* The purpose of the following mexFunction is to let MATLAB know how to call this timestwo function */
Void mexFunction (int nlhs, mxArray * plhs [],
Int nrhs, const mxArray * prhs [])

/* Nlhs is the number of output parameters in MATLAB command line mode;
* Plhs [] is the output parameter in the MATLAB command line mode;
Nrhs is the number of input parameters in MATLAB command line mode;
* Prhs [] is an input parameter in the MATLAB command line mode ;*/

{
Double * x, * y;
Int mrows, ncols;
/* Check for proper number of arguments .*/
If (nrhs! = 1 ){
MexErrMsgTxt ("One input required .");
} Else if (nlhs> 1 ){
MexErrMsgTxt ("Too export output arguments ");
}

/* In the MATLAB command line mode, the calling format of this MEX file is y = timestwo (x)
The number of input parameters (x) is 1, and the number of output parameters (y) is 1.
Check whether nrhs = 1 and nlhs> 1 at the beginning (because MATLAB has a default
Output parameter ans, so the nlhs can be = 0 */
Output parameter ans, so the nlhs can be = 0 */
/* The input must be a noncomplex scalar double .*/

Mrows = mxGetM (prhs [0]);/* obtain the number of rows in the input matrix */
Ncols = mxGetN (prhs [0]);/* obtain the number of columns in the input matrix */
If (! MxIsDouble (prhs [0]) | mxIsComplex (prhs [0]) |
! (Mrows = 1 & ncols = 1 )){
MexErrMsgTxt ("Input must be a noncomplex scalar double .");
}/* Determine whether the input matrix is a double type and whether it only contains a single element */

/* Create a matrix for the output. Obviously, this matrix should also be 1x1 */
Plhs [0] = mxCreateDoubleMatrix (mrows, ncols, mxREAL );
/* Obtain the pointer to the input/output matrix data */
X = mxGetPr (prhs [0]);
Y = mxGetPr (plhs [0]);
/* Call the C ++ function timestwo (y, x )*/
Timestwo (y, x );
}

After the above file is compiled with MEX, the MATLAB command line calls the instance
X = 2;
Y = timestwo (x)
Y =
Y =
4

2. MEX file programming rules
(1) compile your own C ++ Algorithm Program
(2) follow the definition of the mexFunction function. The definition of the mexFunction is unique:
It can only be in the following format:
Void mexFunction (int nlhs, mxArray * plhs [],
Int nrhs, const mxArray * prhs [])
The name and parameter type cannot be changed. You can call the C ++ program you just defined in the mexFunciton function.
3. MEX file Compilation
MATLAB provides a tool for compiling MEX files: mex, which can compile your C ++ source code into a. mex file for MATLAB to call in the command line mode. Enter your C ++ function name (timestwo in the preceding example ). You can use the help mex command in the MATLAB command line.
(3) MAT files
1. Overview
The. MAT file is a data storage format dedicated to MATLAB. Since MATLAB provides a set of API function sets that can be called by MATLAB, we can access the. MAT file in C ++ completely. This means that you can leave the calculation process to MATLAB, and use C ++ to analyze or visualize the calculation results.
2. Interfaces
The API function set provided by MATLAB is encapsulated in the following two standard DLL files: libmat. dll and libmx. dll. The former is used to operate the MAT file, and the latter is used to operate the matrix in the MAT file. Their storage path is <MATLAB> \ bin.
In <MATLAB> \ extern \ include, there are DEF files corresponding to the first two DLL files:
Libmat. edf, libmx. dbf. Its export function prototype is located in the same directory
In mat. h and matrix. h
With these DLL, DEF, and H files, I don't need to say much about how to use C ++ to call API functions.
3. Commonly Used matrix types in MATLAB
· (Complex) Dual-Precision matrix (Complex Double-Precision Matrices)
The most common data types in MATLAB are (complex) Dual-precision and non-sparse matrices. The elements of these matrices are double, and the matrix size is m × n, m indicates the total number of rows and m indicates the total number of columns. Matrix data is actually stored in two dual-precision vectors. One vector stores the real part of the data, and the other vector stores the virtual part of the data. Pointers to these two vectors are generally written as "pr" (pointer to real data, pointer to real data) and "pi" (pointer to imaginary data, pointer to virtual data) ". If the pi of a matrix is null, it indicates that it is a real dual-precision matrix.
· Sparse Matrices)
The storage format of sparse matrix in MATLAB is different. Like a double-precision matrix, it has the pr and pi parameters, and it also has three additional parameters: nzmax, ir, and jc.
Nzmax is an integer whose values are vector ir, pr, and pi (if any. It is the number of non-zero elements in a sparse matrix.
Ir points to an array of integer numbers with a length of nzmax. The array contains the row numbers of the corresponding elements in pr and pi.
Jc points to an array of integer numbers whose length is N + 1 (N is the number of columns in the matrix), which contains the column number information. For any j, if 0 ≤ j ≥ N-1, jc [j] is the sequence number of the first non-zero entry in column j in ir, pr (and pi, jc [j + 1]-1 is the sequence number of the last Non-zero entry in column j. Therefore, jc [N] is equal to the total number of non-zero items in the nnz matrix. If nnz is less than nzmax, you can add non-zero items to the matrix without allocating additional storage space.
.
4. Examples of main functions:
· MATFile * matOpen (const char * filename, const char * mode) -- Open/create
· MATFile * matOpen (const char * filename, const char * mode) -- Open/create a MAT file;
· Int matClose (MATFile * pMF) -- closes a MAT file;
· MxArray * mxCreateDoubleMatrix (int m, int n, mxComplexity flag)
-- Create a (complex) double-precision matrix;
· MxArray * mxCreateSparse (int m, int n, int nzmax, mxComplexity flag)
-- Create a sparse matrix;
· MxArray * matGetNextArray (MATFile * pMF) -- obtains the next matrix in the MAT file;
· Const char * mxGetName (const mxArray * pa) -- Obtain the name of matrix pa;
· Void mxSetName (mxArray * pa, const char * s) -- set a name for Matrix pa;
· Int mxGetM (const mxArray * pa) -- obtains the total number of rows of matrix pa;
· Int mxGetN (const mxArray * pa) -- obtains the total number of columns of matrix pa;
· Double * mxGetPr (const mxArray * pa) -- obtains the pr pointer of matrix pa;
· Int * mxgetio( const mxArray * pa) -- obtains the ir pointer of the sparse matrix pa;
· Int * mxGetJc (const mxArray * pa) -- obtains the jc pointer of the sparse matrix pa;
· Int matPutArray (MATFile * pMF, const mxArray * pA)
-- Store the matrix pA into the MAT file pMAF;
· Void mxDestroyArray (mxArray * pa) -- release matrix pa (remove it from memory );
5. Two examples:
· Obtain the information of the first Matrix in a MAT File
· Obtain the information of the first Matrix in a MAT File
Typedef struct {
Char szFileName [256];
MATFile * pMatFile;
MxArray * pArray;
Char szArrayName [64];
Char szErrMsg [256];
Unsigned int nArrayDim [2];
Bool bIsSparse;
} MATFileStruct;

Int GetMATFileStruct (MATFileStruct * pMAThdr)
{
If (pMAThdr-> pMatFile = matOpen (pMAThdr-> szFileName, "r") = NULL)
{Strcpy (pMAThdr-> szErrMsg, "Can't open this mat file ");
Return (0 );
}/* Open a MAT file */

If (pMAThdr-> pArray = matGetNextArray (pMAThdr-> pMatFile) = NULL)
{Strcpy (pMAThdr-> szErrMsg, "Can't get arrays ");
MatClose (pMAThdr-> pMatFile );
Return (0 );
}/* Obtain the first matrix in the MAT file */
}/* Obtain the first matrix in the MAT file */

PMAThdr-> nArrayDim [0] = mxGetM (pMAThdr-> pArray);/* Get the number of rows */
PMAThdr-> nArrayDim [1] = mxGetN (pMAThdr-> pArray);/* Get the number of columns */
Strcpy (pMAThdr-> szArrayName, mxGetName (pMAThdr-> pArray);/* get its name */
PMAThdr-> bIsSparse = mxIsSparse (pMAThdr-> pArray);/* determine whether it is a matrix of coefficients */
MxDestroyArray (pMAThdr-> pArray);/* undo this matrix in memory */
MatClose (pMAThdr-> pMatFile);/* close the MAT file */
Return (1 );
}

· Create a sparse matrix and assign values
Int I, j, k, m, n, nzmax, * ir, * jc;
Double * pr;
Unsigned short * pData;
MxArray * pa; file: // initialization.
M = pLCMShdr-> TrueHdr. nArrayDim [0]; file: // obtain the number of rows in the original matrix.
N = pLCMShdr-> TrueHdr. nArrayDim [1]; file: // obtain the number of original matrix columns.
Nzmax = 0;

For (I = 0; I <m * n; I ++)
{If (pData! = 0)
Nzmax ++;
Nzmax ++;
} File: // calculate the number of non-zero elements in the data.
If (nzmax <n)
Nzmax = n;

Pa = mxCreateSparse (m, n, nzmax, mxREAL);/* Create an empty sparse matrix pa. */
MxSetName (pa, pLCMShdr-> TrueHdr. szArrayName);/* set the name for the sparse matrix pa. */
Pr = mxGetPr (pa); file: // get the pr pointer of pa.
Ir = mxgetio( pa); file: // obtain the ir pointer of pa.
Jc = mxGetJc (pa); file: // obtain the jc pointer of pa.

K = 0;
For (j = 0; j <n; j ++)
{Jc [j] = k; file: // jc [j]: Number of non-zero elements as of column j.
For (I = 0; I {if (pData! = 0) file: // If the element in row I of column j is a non-zero element.
{Ir [k] = I; file: // record the row number of the k non-zero element.
K ++;
}
}
PData + = m; file: // move the pData pointer to the next column.
}

Jc [n] = k; file: // jc [n] is equal to the number of non-zero elements in the matrix.
MatPutArray (pmat, pa); file: // store the sparse matrix pa to the MAT file pmat.
MxDestroyArray (pa); file: // detaches the matrix pa from the memory.
(5) Engine Applications
1. Introduction
The essence of an engine application is to use MATLAB as an engine, which allows you to call this engine from your own C ++ program. During running, the engine runs independently as a process, and your C ++ program runs independently as a process. The two can interact through the communication mechanism between processes.
2. Engine Library
The MATLAB Engine library contains several functions that control the MATLAB Engine, as shown below:
EngOpen starts the MATLAB Engine
EngClose closes the MATLAB Engine
EngGetArray obtains a MATLAB matrix from the MATLAB Engine.
EngPutArray sends a MATLAB matrix to the MATLAB Engine
EngEvalString is executed on a MATLAB command
EngOutputBuffer creates a buffer for storing MATLAB text output.
At the same time, engine applications can also use the previously mentioned API functions.
3. An example
In this example, we can see how engine applications are compiled:
/* $ Revision: 1.3 $ */
/*
* Engdemo. c
*
* This is a simple program that calls strates how to call
* MATLAB engine functions from a C program.
*
* Copyright (c) 1996-1998 The MathWorks, Inc.
* All rights reserved
*/
# Include
# Include
# Include
# Include "engine. h"
# Define BUFSIZE 256
Int main ()
{
Engine * ep;
MxArray * T = NULL, * result = NULL;
Char buffer [BUFSIZE];
Double time [10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,
8.0, 9.0 };
8.0, 9.0 };
6-6
/*
* Start the MATLAB engine locally by executing the string
* "Matlab ".
*
* To start the session on a remote host, use the name
* The host as the string rather than {post. content}
*
* For more complicated cases, use any string with whitespace,
* And that string will be executed literally to start MATLAB.
*/
If (! (Ep = engOpen ("{post. content }"))){
Fprintf (stderr, "\ nCan't start MATLAB engine \ n ");
Return EXIT_FAILURE;
}/* Start the MATLAB Engine */
/*
* PART I
*
* For the first half of this demonstration, we will send data
* To MATLAB, analyze the data, and plot the result.
*/
/*
/*
* Create a variable for our data.
*/
T = mxCreateDoubleMatrix (1, 10, mxREAL);/* Create a matrix */
MxSetName (T, "T");/* set the matrix name to "T "*/
Memcpy (void *) mxGetPr (T), (void *) time, sizeof (time);/* assign a value to the matrix "T */
/*
* Place the matrix "T" into the MATLAB Engine
*/
EngPutArray (ep, T)
/*
* Evaluate a function of time, distance = (1/2) g. * t. ^ 2
* (G is the acceleration due to gravity ).
*/
EngEvalString (ep, "D =. 5. * (-9.8). * T. ^ 2;");/* execute MATLAB
Command: D =. 5. * (-9.8). * T. ^ 2 ;*/
/*
* Draw an image.
*/
EngEvalString (ep, "plot (T, D);");/* execute the MATLAB command: Drawing */
EngEvalString (ep, "title ('position vs. Time for a falling
Object '); ");/* execute the MATLAB command: Add a title to the image */
EngEvalString (ep, "xlabel ('time (seconds) ');");/* run the MATLAB command: Set the X axis coordinate */
EngEvalString (ep, "xlabel ('time (seconds) ');");/* run the MATLAB command: Set the X axis coordinate */
EngEvalString (ep, "ylabel ('position (meters) ');");/* run the MATLAB command: Set the Y axis
Coordinates */
/*
* Use fgetc () to make sure that we pause long enough to be
* Able to see the plot.
*/
Printf ("Hit return to continue \ n ");
Fgetc (stdin );
/*
* We're done for Part I! Free memory, close MATLAB engine.
*/
Printf ("Done for Part I. \ n ");
MxDestroyArray (T);/* remove the matrix "T" from the memory "*/
EngEvalString (ep, "close;");/* close the window showing the image just now */
/*
* PART II
*
* For the second half of this demonstration, we will request
* A MATLAB string, which shoshould define a variable X. MATLAB
* Will evaluate the string and create the variable. We
* Will then recover the variable, and determine its type.
*/
*/
/*
* Use engOutputBuffer to capture MATLAB output, so we can
* Echo it back.
*/
EngOutputBuffer (ep, buffer, BUFSIZE);/* construct the MATLAB text input buffer */
While (result = NULL ){
Char str [BUFSIZE];
/*
* Get a string input from the user.
*/
Printf ("Enter a MATLAB command to evaluate. This
Command shoshould \ n ");
Printf ("create a variable X. This program will then
Determine \ n ");
Printf ("what kind of variable you created. \ n ");
Printf ("For example: X = 1:5 \ n ");
Printf (">");/* Ask the user to enter a MATLAB command */
Fgets (str, BUFSIZE-1, stdin);/* Get user input */
/*
* Evaluate input with engEvalString.
*/
EngEvalString (ep, str);/* execute the MATLAB command entered by the user */
EngEvalString (ep, str);/* execute the MATLAB command entered by the user */
/*
* Echo the output from the command. First two characters
* Are always the double prompt (> ).
*/
Printf ("% s", buffer + 2);/* displays the execution status of the MATLAB command */
/*
* Get result of computation.
*/
Printf ("\ nRetrieving X... \ n ");
If (result = engGetArray (ep, "X") = NULL)/* determines whether MATLAB
Obtain the matrix "X" in the engine "*/
Printf ("Oops! You didn't create a variable X. \ n ");
Else
Printf ("X is class % s \ t \ n", mxGetClassName (result);/* display matrix "X"
Type */

}/* While (result = NULL )*/
/*
* We're done! Free memory, close MATLAB engine and exit.
*/
Printf ("Done! \ N ");
MxDestroyArray (result);/* remove the matrix "T" from the memory "*/
EngClose (ep);/* disable the MATLAB Engine */
Return EXIT_SUCCESS;/* return */
}
4. Engine Application Compilation
For the console program in the preceding example, you can directly compile it using the mex command with the-f parameter in the MATLAB command line.
If the MATLAB Engine is used in a common win32 application, the situation is complicated. In Windows, the MATLAB Engine is called through ActiveX. Therefore, you must first Create an OLE Automation Sever and an OLE Client, and then call this MATLAB Engine through OLE. For more information, see the relevant MATLAB random document.
5. Summary
The call of the MATLAB Engine is similar to that of other engines (such as the database engine). The procedure is to connect to or start the engine, and then send commands to the engine to obtain the engine processing result.

Conclusion
The above briefly introduces several methods of interfaces between MATLAB and C ++. we can adopt the corresponding methods according to different requirements.
In addition, MATLAB also provides a mathematical library, from which we can obtain more access and more flexible access to MATLAB Internal commands. For details, refer to the relevant random document of MATLAB.
· References
1. MATLAB random document: apiguidemo-
2. MATLAB random document: apiref.pdf
3. MATLAB random document: c_math_ref1.pdf
· Thanks
Thanks to loverboy for his encouragement, he claimed that he would put these posts on his homepage so that I could finish this article on interface problems in a short time, Xi.
· Remarks
For more information about how to configure the mex compiler in VC6, see section 19 #.
Comments of Bluesky:
It is best for VC programmers to use visual matcom. VB uses matrixVB mathtool to provide a free trial on the homepage. Go to the next page. Matlab functions can be implemented in your VC and VB, and can be released with only two dll files.
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.