Reproduced C-mex Program Writing

Source: Internet
Author: User
Tags scalar

Original author, Hu Rongchun 2006-10-11

1About MEX Files

The C or Fortran language program that can be called in MATLAB is called a Mex file. MATLAB can call the Mex file directly as its built-in function. The Mex file is a dynamically linked subroutine that can be loaded and executed automatically by the MATLAB interpreter.

Mex files are mainly used for the following purposes:

1. For a large number of existing C or FORTRAN programs can not be rewritten to the MATLAB dedicated m file format and executed in MATLAB .

2. For those algorithms that are too slow for MATLAB, they can be written in C or Frotran language to raise efficiency .

2Example

Prepare for a detailed format. Below is the instance 1.

#include "mex.h"

/* TIMESTWO.C The purpose of this Mex file is to achieve the function of times one */

void Timestwo (double y[], double x[])

{

Y[0] = 2.0*x[0];

}

/* The purpose of this mexfunction is to make Matlab know how to call this Timestwo function

NLHS is the number of output parameters in MATLAB command line mode;

*plhs[] is the output parameter of MATLAB command line mode;

NRHS is the number of input parameters under MATLAB command line mode;

*prhs[] is the input parameter under MATLAB command line mode; */

void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])

{

Double *x,*y; Double pointer type cannot be changed!!

int mrows,ncols;

/* Check for proper number of arguments. */

if (nrhs!=1)

Mexerrmsgtxt ("One input required.");

else if (nlhs>1)

Mexerrmsgtxt ("Too Many output arguments");

/* in the MATLAB command line mode, the invocation format of this MEX file is Y=timestwo (x). Input parameter (x) Number = 1, output parameter (y) Number = 1, so in program one

Start by checking whether the NRHS =1 and NLHS are >1 (because MATLAB has a default output parameter ans, so nlhs can be = 0 */

Mrows = Mxgetm (Prhs[0]); /* Get the number of rows in the input matrix */

Ncols = MXGETN (Prhs[0]); /* Get 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 if the input matrix is a double class, and whether it includes only a single element * /

/* Create a matrix for the output, obviously this matrix should also be 1x1 */

Plhs[0] = Mxcreatedoublematrix (Mrows,ncols, mxreal);

x = MXGETPR (prhs[0]); /* Get pointers to input/output matrix data */

y = MXGETPR (plhs[0]);

Timestwo (Y,X); /* Call C function Timestwo (y,x) */

}

After editing the above file timestwo.c, in the MATLAB command line, enter:

Mex TIMESTWO.C

Matlab will prompt you to choose a compiler to compile, if the VC installed, then choose VC + + can. The dynamic link library file Timestwo.dll with the same name will be generated in the same directory when the compilation is complete. When you then enter "Mex ***.c" to compile the Mex file, the user is no longer prompted to select the compiler, and the default compiler compilation is automatically selected. If you want to change the compiler to compile, you can enter "Mex Timestwo.c–setup".

You can use this dynamic link library once the compilation is complete. Under the MATLAB command line, enter:

x = 2;

y = timestwo (x)

will be displayed:

y =

4

3MEX file Format detailed

First compile your own C algorithm program, followed by the definition of mexfunction function, the definition of mexfunction is unique, it can only be the following form:

void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])

The name and parameter types are not allowed to change, and the C program you just defined can be called in the Mexfunciton function.

3.1 Parameter definitions

As an example of the timestwo.c file above, when you enter "y = timestwo (x)" on the MATLAB command line after compilation, MATLAB loads the timestwo.dll dynamic link library file. Timestwo.dll (Mexw32, MEXW64) executes the Mexfunciton function first, and the value "2" of the input parameter x is passed to Prhs[0], and the number of input parameters "1" is passed to PLHS. Since the variables in MATLAB are stored in a double type, the C type of all input and output parameters in the MEX program should be double. This is also why the previous example defines "double *x,*y;" The reason that must be a double pointer type. and also note that it must be Double pointer, cannot be a double only .

3.2 Input and output parameter check

The next step is to check the input parameters to determine if the number of input parameters is in accordance with the definition, otherwise give the error message.

3.3 Parameter Hook up

After the parameter check is completed is the corresponding input and output parameters of the hook (for a moment to think of a better word, where the term "hook" is used to express the following meaning):

/* Create a matrix for the output, obviously this matrix should also be 1x1 */

Plhs[0] = Mxcreatedoublematrix (Mrows,ncols, mxreal);

x = MXGETPR (prhs[0]); /* Get pointers to input/output matrix data */

y = MXGETPR (plhs[0]);

This first creates a matrix for the output parameter. Note that regardless of whether the output is a matrix or a scalar, a separate matrix must be created for all output parameters. in the case of scalars, the rows and columns are set to 1 when they are created:

Mxcreatedoublematrix (Mxreal);

The reason for this is that every variable in MATLAB is in the form of a matrix.

Prhs[] and plhs[] are not directly used in the program, you must define the corresponding pointer variable. Therefore, a pointer to an interface parameter and a pointer to a parameter in the program are used to hook up, i.e. "x = MXGETPR (prhs[0]);" The work that the statement does. See here you should understand why all the input and output parameters inside the void Mexfunction function must be defined as a double pointer. Because all defined parameters must be hooked up with prhs[], plhs[].

3.4 Calling Function functions

After the parameter hook is complete, you can invoke the function function that you wrote:

Timestwo (Y,X); /* Call C function Timestwo (y,x) */

It is important to note that the input parameters of the call are consistent with the defined parameters. as the Timestwo () function is defined as follows:

void Timestwo (double y[], double x[])

Two parameters are pointer type, so call "Timestwo (y,x);" The input is a "y,x" two pointers. And if the Timestwo () function is defined as:

void Timestwo (double y[], double x)

The input parameter x should be a variable of type double, when the input parameter can be written as:

Timestwo (Y,x[0]);

3.5 Writing of function functions

The writing of functional functions depends on the functionality that the user wants to accomplish. The following 2 points are worth presenting here:

(1) The function name is not directly related to the function names that are called in MATLAB, but only the function names that are called in mexfunction. The function name called by Matlab depends on the last generated DLL file name, which can be changed arbitrarily (but the first letter cannot be a number).

(2) The function function has no return value, is a void type, and the output parameter that the entire DLL module eventually returns to Matlab is included in the input parameters of the function function. Since the input and output parameters described above need to be hooked up, the final output parameter in the input parameter of the function function must be defined as a double pointer type , such as: "Void Timestwo (double y[], Double x) ". Where Y is the final output parameter and must be a double pointer type, and the input parameter from MATLAB is defined as the pointer type, depending on the case.

3.6 Example 2

This example is the program to complete the Dijkstra shortest path algorithm.

#include "mex.h"

/* Shortest path to the specified node for all nodes in the network, Dijkstra algorithm */

#define INFN 1000

#define INFI 10000

void F_dijkstra_all (double *w, double *d, unsigned long n, unsigned long p)

{

unsigned long I,J,WTMP,PNEW,NU=N-1,NP=1;//NP is the number of known distance nodes, Nu is the number of unknown distance nodes, IDP is the known node ID

unsigned long IDU[INFN], IDP[INFN]; Unknown node Idu, known node IDP

p--;

Idp[0]=p;

for (i=0;i<n;i++)

{

W[I]=D[N*I+P];

if (i<p)

Idu[i]=i;

Else

idu[i]=i+1;

}

while (NU)

{wtmp=infi;

for (i=0;i<nu;i++)

{for (j=0;j<np;j++)

if (w[idp[j]]+d[N*idp[j]+idu[i]] < w[idu[i])

w[idu[i]]=w[idp[j]]+d[N*idp[j]+idu[i]];

if (W[idu[i]]<infi && W[idu[i]] < wtmp)

{Wtmp=w[idu[i]];

Pnew=i;

}

}

if (WTMP<INFI)

{Idp[j]=idu[pnew];

np++;

for (i=0;i<nu;i++)//idu (pnew) =[];

if (i>=pnew)

IDU[I]=IDU[I+1];

nu--;

}

Else

nu=0;

}

}

/* The purpose of this mexfunction is to make Matlab know how to call this function */

void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])

{

if (nrhs!=3)

Mexerrmsgtxt ("Three input required.");

else if (nlhs>1)

Mexerrmsgtxt ("Too Many output arguments");

Mrows = Mxgetm (Prhs[0]); /* Get the number of rows in the input matrix */

Ncols = MXGETN (Prhs[0]); /* Get the number of columns in the input matrix */

if (Mxiscomplex (Prhs[0]))

Mexerrmsgtxt ("Input must be a noncomplex."); /* Determine if the input matrix is plural */

Plhs[0] = Mxcreatedoublematrix (1,ncols, mxreal); /* Create a matrix for the output */

D = MXGETPR (Prhs[0]); /* Get pointers to input/output matrix data */

n = MXGETPR (prhs[1]);

p = MXGETPR (prhs[2]);

W = MXGETPR (Plhs[0]);

F_dijkstra_all (W, D, N[0], p[0]); /* Call C function */

}

4Additional Information

When writing a function function, it is important to note that when a matrix inmatlab is passed into an array in C, the order of the elements is sorted by the first column.

For example: a matrix D as an input parameter, this matrix is:

D=[1 2 3

4 5 6]

When you attach this input parameter to a defined double pointer variable dp, write down the element that the DP points to, and you will find:

Dp[0]=1

Dp[1]=4

dp[2]=2

Dp[3]=5

Dp[4]=3

Dp[5]=6

Therefore, to correctly refer to the elements in the first row of column J of the original matrix, you should use dp[i-1+ (j-1) *n]. where n is the number of rows of the matrix.

Reference documents

MATLAB and C Interface problem Classification: My technology I am the Master, Beijing Polytechnic University BBS

Reproduced C-mex Program Writing

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.