Visual c ++ is one of the mainstream application development environments. The development environment is powerful and the development process is fast. In terms of scientific computing, function libraries are not rich enough, and it is inconvenient to read and display data graphs. MATLAB is a combination of numerical analysis, matrix computing, signal processing, and graphic display. It contains a large number of highly integrated functions for calling, it is a simple and efficient programming tool suitable for scientific research, engineering design, and other fields. However, Matlab uses an explanatory language, which greatly limits its execution speed and application scenarios. Hybrid programming based on VC and Matlab is a common method for many researchers who are familiar with VC ++ programming and need scientific computing and data simulation, the simplest and most direct method is to call the Matlab Engine. The following sections describe how to use VC ++ 6.0 to call the Matlab Engine to achieve data sharing programming between VC ++ and Matlab.
1. What is the 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. Main functions include:
★Enable/disable a MATLAB conversation;
★Send command strings to the MATLAB environment;
★Read data from the MATLAB environment;
★Write Data to the MATLAB environment.
Compared with other interfaces, the Matlab function supported by the engine is the most comprehensive. Through the engine, the application opens a new MATLAB process, which can be controlled to complete any computing and drawing operations. 100% support for all data structures. At the same time, the MATLAB process opened in the engine mode will display its own icon in the taskbar, open this window, you can observe that the main program controls the MATLAB running process through the engine mode, you can also enter any MATLAB command.
In fact, a conversation established through an engine starts Matlab as an ActiveX control. When Matlab is first installed, it is automatically executed once:
MATLAB/regserver
Register yourself in the control library of the system. If you cannot open the Matlab Engine for special reasons, you can run the preceding command at the doscommand prompt and re-register it.
2. Configure the Compiler
To successfully compile the Matlab Engine program in VC, it must contain the engine header file engine. h and introduce the library file libmx. Lib, libmat. Lib, and libeng. Lib corresponding to Matlab. Specifically, after opening a project, make the following settings (take vc6 as an example ):
1) Open the setting properties page through the menu Project/option, go to the directories page, select include files in the directory drop-down list box, and add the path: "C: \ MATLAB \ extern \ include "(assuming that MATLAB is installed in the C: \ MATLAB directory ).
2) Select library files and add the path c: \ MATLAB \ extern \ Lib \ Win32 \ Microsoft \ msvc60.
3) Open the properties page of Project settings through the menu Project/settings, enter the link page, and add the file name libmx. Lib libmat. Lib libeng. Lib in the object/library modules editing box.
The preceding steps 1), 2) only need to be set once, and 3) Each project must be set separately. For other C ++ compilers such as Borland C ++ builder, the settings are roughly the same, I will not go into details.
3. Engine API details
Before calling the Matlab Engine, add a line in the relevant file: # include "enging. H", which contains the description of the engine API function and the definition of the required data structure. The engine functions that can be called in VC are as follows:
3.1 enable and disable the 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 can only be null in windows.
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. { MessageBox ("can't start Matlab Engine! "); Exit (1 ); } ............. Engclose (EP); // disable the Matlab Engine. |
3.2 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.3 obtain the output of the MATLAB command window
To obtain the command string sent by the engevalstring function in VC and output it in the MATLAB window after being executed by MATLAB, you can call the engoutputbuffer function.
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 ).
3.4 read and write MATLAB data
3.4.1 obtain variables from the Matlab Engine workspace.
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 return value is a pointer to the name array and the type is mxarray * (mxarray data type is described in Section 4th ).
3.4.2 write variables to the Matlab Engine workspace.
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.5 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.
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:
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.
4. Data-type mxarray operations
In the above Matlab Engine functions, all data types related to variables are mxarray. Mxarray and a large number of functions starting with Mx are widely used in Matlab Engine programs and matlab c math libraries. Mxarray is a complex data structure, which corresponds to the array in MATLAB. We only need to be familiar with the array type of MATLAB and several common mxarray functions.
In VC, all data interactions with Matlab are implemented through mxarray. In a program using mxarray, the header file matrix should be included. h. However, in engine programs, the header file engine is generally included. h. The file already contains matrix. h, so you do not need to include it again.
4.1 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.
The establishment of an array is a function in the form of mxcreatexxx. For example, to create a double type array, you can use the mxcreatedoublematrix function. The function form is as follows:
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.
For example, to delete the created array T, you can use the following statement:
Similar functions include:
Mxarray * mxcreatestring (const char * Str ); |
Create a string type and initialize it as a STR string.
Generally, in the interaction between VC and MATLAB, the above two types are enough. The creation of other types of arrays is not described here.
4.2 manage mxarray Data Types
4.2.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. |
4.2.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 simple, self-explanatory, and will not be explained.
4.2.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. For detailed implementation, see section 5th program instance.
5. program instance
It is convenient and efficient for most software developers to use VC programming, but it is not so easy to display data graphics. At this time, it is not necessary to use Matlab Engine to assist in drawing data analysis. The following example demonstrates how to use VC to call MATLAB plotting. The main function of the program is to calculate the function value Y = sin (x) ± log (x) for Array X in VC ), then, call MATLAB to draw the Y-to-x graph.
Create a project in VC and write the following code:
# Include <iostream> # Include <math. h> # Include "engine. H" Using namespace STD; Void main () { Const int n = 50; Double X [N], Y [N]; Int J = 1; For (INT I = 0; I <n; I ++) // calculates arrays X and Y { X [I] = (I + 1 ); Y [I] = sin (X [I]) + J * log (X [I]); // the random number between generate-is assigned to XX [I]; J * =-1; } Engine * EP; // defines the Matlab Engine pointer. If (! (Ep = engopen (null) // test whether the Matlab Engine is successfully started. { Cout <"can't start Matlab Engine! "<Endl; Exit (1 ); }// Defines mxarray as a real array of rows and columns n. Mxarray * xx = mxcreatedoublematrix (1, n, mxreal ); Mxarray * YY = mxcreatedoublematrix (1, n, mxreal); // same as above. Memcpy (mxgetpr (XX), X, N * sizeof (double); // copy array X to mxarray array xx. Memcpy (mxgetpr (yy), y, N * sizeof (double); // copy array X to mxarray array yy. Engputvariable (Ep, "XX", XX); // write the mxarray array XX to the MATLAB workspace and name it xx. Engputvariable (Ep, "YY", YY); // write the mxarray YY to the MATLAB workspace and name it yy. // Send a drawing command to the Matlab Engine. Plot is a graph function of MATLAB. For more information, see MATLAB documentation. Engevalstring (Ep, "plot (XX, YY );"); Mxdestroyarray (XX); // destroy the mxarray array XX and yy. Mxdestroyarray (yy ); Cout <"press any key to exit! "<Endl; Cin. Get (); Engclose (EP); // disable the Matlab Engine. } |
Compile and run the program. The result is as follows:
6. Summary
This article describes in detail how to use the Matlab Engine and demonstrates a simple example of using VC to call the MATLAB drawing program. Most of the time, programmers can use MATLAB's powerful Data Reading and Writing capabilities and VC programming efficiency. For example, to read an image of any format in MATLAB, you only need one command I = imread ('test. JP '); the image data matrix is stored in two-dimensional array I. You can use VC to read the array for processing and then call MATLAB to display it. This hybrid programming method can greatly improve work efficiency.
Of course, the Matlab Engine program compiled by VC must also be supported by MATLAB in the runtime environment. If you want to compile a program completely out of Matlab, you can use other methods, for example, use a third-party MATCOM program to compile an independent executable program.
From http://dev.yesky.com/300/2343300_3.shtml