Interface Specification for mexfunction functions in MATLAB (reprint)

Source: Internet
Author: User
Tags scalar

The Mex file is very convenient to call and is called in exactly the same way as the built-in function of Matalab, just enter the corresponding file name in the command window.

The C Language Mex program code file has a computational subroutine (computational routine) and an interface subroutine (Gatway routine) consisting of two separate sub-routines. The function of the computational subroutine is to complete the calculation required, it is the same as the General C source program file with the same function, and the function of the socket program is to compute the interface between the subroutine and the Matalab, and the user realizes the communication between the two different memory spaces.

void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
NLHS: Number of output parameters (left-hand side)
PLHS: Pointer to output parameter
NRHS: Number of input parameters
For example, using
[A,b]=test (c,d,e)
when invoking the MEX function test, the three parameters passed to test are Prhs[0]=c,Prhs[1]=d,prhs[2]=e
when the function returns, the address you put in the plhs[0],plhs[1] is assigned to A and B, to return the data.
carefully you may have noticed that prhs[i] and plhs[i] are pointers to the type Mxarray type data. This type is defined in mex.h, in fact, most of the data in MATLAB exists in this type. Of course there are other data types that can be referenced in apiguide.pdf.
to give you a more intuitive understanding of the process of parameter passing, let's rewrite the hello.c so that it can be based on the output
changes to the input parameters give 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 this program, execute hello (1) and the screen will be typed:
hello,world!
and Hello (0) will get:
Hello, everyone!
now, the program hello can already give the corresponding screen output according to the input parameters. In this program, in addition to the use of the screen output function mexprintf (the use of the printf function in C is almost exactly the same), also used a function: Mxgetscalar, called as follows:
i=mxgetscalar (prhs[0]);
"scalar" is the meaning of scalar. In MATLAB, the data is in the form of an array, the function of Mxgetscalar is to pass through the prhs[0] Mxarray type pointer to the data (scalar) assigned to the variables in the C program. This variable is supposed to be of type double and is assigned to the shaping variable I by forcing the type conversion. Since there are scalars, obviously there should be vectors, 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[])

double *i;
I=MXGETPR (prhs[0]);
if (i[0]==1)
mexprintf ("hello,world!\n");
Else
mexprintf ("Hello everyone!") \ n ");
}  
Thus, a pointer to a double type is obtained from the MXGETPR function from the prhs[0 of 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? Only pointers to this matrix can be obtained through MXGETPR, and if we do not know the exact size of this matrix,
It is impossible to calculate it.
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 pointers to matrices
M=mxgetm (prhs[0]);//Gets the number of rows of the matrix
N=mxgetn (prhs[0]);//Gets the number of columns of the 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 it 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, whereas in C, the first line is ordinal zero, and the matrix element B (i,j) in MATLAB corresponds to Data[j*m+i] after the large data of one-dimensional array passed to C.
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 parameter needs to be applied to the memory space within the MEX function to pass the pointer over plhs[]. Since the return pointer type must be Mxarray, MATLAB specifically provides a function: Mxcreatedoublematrix to implement the memory application, the function prototype is as follows:
mxarray *mxcreatedoublematrix (int m, int n, mxcomplexity complexflag)
m: Number of rows to be applied to the matrix
N: Number of columns to apply for matrix
after applying the memory for the matrix, we get a pointer of type Mxarray, which can be passed back in plhs[]. However, the processing of this new matrix is done within the function, and it is necessary to use the MXGETPR described earlier. After using MXGETPR to obtain a pointer (double type) that points to the data area in the matrix, you can perform various operations and operations on the matrix. The following program is a slight change on the basis of the above show.c, 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, MATLAB is not only used in the matrix of double type, there are string type, sparse matrix, struct type matrix and so on, and provide the corresponding processing function. In this paper, we use some of the most frequently encountered functions in the preparation of Mex programs, and the rest of the details refer to apiref.pdf.
through the introduction of the previous two parts, we should have a basic understanding of the input and output methods of the parameters. With this knowledge, you can meet the general programming needs. However, these programs have a few minor flaws, the previous introduction of the re because the previous routines do not have the input, output parameter number and type of check, resulting in a poor program fault tolerance, the following program is better fault tolerance
#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 running of the current program while giving the error prompt. Mxisdouble is used to determine whether the data in the Mxarray is a double type. Of course, MATLAB also provides many functions for judging other data types, which are not detailed here.
It should be explained that in the API provided by MATLAB, the function prefix has mex-and mx-two kinds. Most of the mx-prefixes are functions that operate on mxarray data, such as Mxisdouble,mxcreatedoublematrix and so on. The MEX prefixes are mostly functions that interact with the MATLAB environment, such as Mexprintf,mxerrmsgtxt, and so on. Knowing this, it is helpful to find the required functions in apiref.pdf.
So far, usec The basic process of writing a MEX function has been introduced.

Interface Specification for mexfunction functions in MATLAB (reprint)

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.