MATLAB and C/C + + mixed programming matlab Call the program

Source: Internet
Author: User
Tags function prototype mixed scalar

You can speed up execution by using a long function in C language and compiling the MEX function. MATLAB itself is not with C language compiler, so require your machine has been installed VC,BC or watcom C. If you have set up the compiler in the installation of MATLAB, you should now be able to use the MEX command to compile the C language program. If there is no election, in the MATLAB type Mex-setup, as long as the following prompts step-by-step settings can be. It should be noted that earlier versions of the compiler path can only use the 8-character form of the path name. For example, I used the VC installed in the path C:/Program Files/devstudio, that in the setting of the path will be written: "C:/progra~1" so set up, MEX can be executed. To test your path settings correctly, save the following program as a hello.c.
/*hello.c*/
#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
{mexprintf ("hello,world!/n");
}
Let's say you put the hello.c in the c:/test/, use CD c:/test/in MATLAB to change the current directory to c:/ test/(Note that it is no use to add c:/test/to the search path only). Knock Now:
Mex HELLO.C
If all goes well, the compilation should exit normally after the compiler prompts. If you have the c:/test/added
In the search path, now type Hello, and the program will play a line on the screen:
hello,world!
Look at the c/test/directory and you'll find one more file: HELLO.DLL. In this way, the first MEX function is complete. Analysis of HELLO.C, you can see that the structure of the program is very simple, the entire program from a process of access mexfunction composition.
void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
Mentioned earlier, the MEX function of MATLAB has a certain interface specification, means that this
NLHS: Number of output parameters
PLHS: pointer to output parameter
NRHS: Number of input parameters
For example, use
[A,b]=test (C,d,e)
When the MEX function test is invoked, the four parameters passed to test are
2,plhs,3,prhs
which
Prhs[0]=c
Prhs[1]=d
Prhs[2]=e
When the function returns, the address you put in plhs[0],plhs[1] will be assigned to a and B to achieve the return data.
Careful as you may have noticed, prhs[i] and plhs[i are pointers to type Mxarray type data. This type is defined in mex.h, in fact, most of the data in MATLAB is in this type. Of course there are other data types, you can refer to the introduction of apiguide.pdf.
In order for us to have a more intuitive understanding of the process of parameter transfer, we rewrite the hello.c so that it can be based on the loss
The variation of the input parameters gives different screen outputs:
HELLO.C 2.0
#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
{
int i;
I=mxgetscalar (Prhs[0]);
if (i==1)
mexprintf ("hello,world!/n");
Else
mexprintf ("Hello, everyone.") /n ");
}
After compiling the program, execute hello (1) and the screen will be typed:
hello,world!
and hello (0) will get:
Hello everyone.
Now, the program hello already can give the corresponding screen output according to the input parameters. In this program, in addition to using the screen output function mexprintf (usage is almost exactly the same as the printf function in c), a function is used: Mxgetscalar, which is called as follows:
I=mxgetscalar (Prhs[0]);
"Scalar" is the meaning of scalar. In the MATLAB data are in the form of an array, the role of Mxgetscalar is to pass through the prhs[0] passed in the Mxarray type of pointer to the data (scalar) to the C program variables. This variable is supposed to be a double type, and is assigned to the shape variable i by force type conversion. Since there is a scalar, obviously there should be a vector, otherwise the matrix can not be transmitted. Look at the following program:
HELLO.C 2.1
#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[],
int NRHS, const mxarray *prhs[])
{
int *i;
I=MXGETPR (Prhs[0]);
if (i[0]==1)
mexprintf ("hello,world!/n");
Else
mexprintf ("Hello, everyone.") /n ");
}
Thus, a pointer to the type double is obtained from the MXGETPR function from the prhs[0 that points to the Mxarray type data.
However, there is a problem, if the input is not a single data, but the vector or matrix, then how to deal with it. By MXGETPR we can only get pointers to this matrix, if we don't know the exact size of the matrix, we
It can't be calculated.
To solve this problem, MATLAB provides two functions Mxgetm and MXGETN to get the number of rows and columns passed in the parameters. The function of the following routine is simply to get the input matrix and display it on the screen:
SHOW.C 1.0
#include "mex.h"
#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
{
Double *data;
int m,n;
int i,j;
DATA=MXGETPR (Prhs[0]); Get a pointer to a matrix
M=mxgetm (Prhs[0]); Get the number of rows in a matrix
N=MXGETN (Prhs[0]); Get the number of columns in a matrix
for (i=0;i<m;i++)
{for (j=0;j<n;j++)
mexprintf ("%4.3f", Data[j*m+i]);
mexprintf ("n");
}
}
Once the compilation is complete, test with the following command:
A=1:10;
B=[A;A+1];
Show (a)
Show (b)
It should be noted that in MATLAB, the first line of the matrix is starting from 1, and in C language, the first line ordinal number is zero, matlab matrix element B (i,j) is passed to C in the one-dimensional array of large data corresponding to Data[j*m+i].
The input data is in MATLAB before the function call has applied for memory, because the MEX function and MATLAB share the same address space, so in prhs[] pass the pointer can achieve the purpose of parameter transfer. However, the output parameters need to be applied to the memory space within the MEX function to pass the pointer over the plhs[]. Since the return pointer type must be Mxarray, MATLAB specifically provides a function: Mxcreatedoublematrix to implement the memory request, the function prototype is as follows:
Mxarray *mxcreatedoublematrix (int m, int n, mxcomplexity complexflag)
M: Number of rows to be requested matrix
N: The number of columns to be requested matrix
After applying the memory for the matrix, we get the Mxarray type of pointer, which can be passed back in the plhs[. But the processing of this new matrix is done within the function, which requires the MXGETPR described earlier. After you use MXGETPR to obtain a pointer to the data area in this matrix (double type), you can perform various operations and operations on the matrix. The following program is based on the above show.c to make a slight change, the function is to lose
REVERSE.C 1.0
#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[],
int NRHS, const mxarray *prhs[])
{
Double *indata;
Double *outdata;
int m,n;
int i,j;
INDATA=MXGETPR (Prhs[0]);
M=mxgetm (Prhs[0]);
N=MXGETN (Prhs[0]);
Plhs[0]=mxcreatedoublematrix (M,n,mxreal);
OUTDATA=MXGETPR (Plhs[0]);
for (i=0;i<m;i++)
for (j=0;j<n;j++)
outdata[j*m+i]=indata[(N-1-J) *m+i];
}
Of course, the use of MATLAB is not only a double type of the matrix, there are string types, sparse matrix, structure type matrix, and so on, and provide the corresponding processing functions. This article uses to compile the MEX program most often encounters the function, the remainder detailed situation clear reference apiref.pdf.
Through the previous two parts of the introduction, we have the parameters of the input and output methods should have a basic understanding. With this knowledge, you can meet the general programming needs. But these programs still have some minor flaws, with the re described in the previous routine, the number and type of input and output parameters are not checked, which results in poor fault tolerance of the program, and the following procedures are better fault-tolerant
#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
{
Double *indata;
Double *outdata;
int m,n;
Exception handling
Exception handling
if (nrhs!=1)
Mexerrmsgtxt ("Usage:b=reverse (a)/n");
if (!mxisdouble (Prhs[0]))
Mexerrmsgtxt ("The Input Matrix must be double!/n");
INDATA=MXGETPR (Prhs[0]);
M=mxgetm (Prhs[0]);
N=MXGETN (Prhs[0]);
Plhs[0]=mxcreatedoublematrix (M,n,mxreal);
OUTDATA=MXGETPR (Plhs[0]);
for (i=0;i<m;i++)
for (j=0;j<n;j++)
outdata[j*m+i]=indata[(N-1-J) *m+i];
}
In the above exception handling, two new functions were used: Mexerrmsgtxt and mxisdouble. Mexerrmsgtxt exits the current program while giving an error prompt. Mxisdouble is used to determine whether the data in the Mxarray is a double type. Of course, Matlab also provides a number of functions to determine other data types, not in detail here.
What needs to be explained is, MATLAB provides the API, the function prefix has mex-and mx-two kinds. Most of the mx-prefixes are functions that manipulate mxarray data, such as Mxisdouble,mxcreatedoublematrix, and so on. And with the MX prefix is mostly with the MATLAB environment interaction functions, such as mexprintf,mxerrmsgtxt and so on. With this in mind, it's helpful to find the function you want in apiref.pdf.
So far, the basic process of writing MEX functions using C has been introduced.  

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.