Matlab C Mixed Programming __ programming

Source: Internet
Author: User
Tags array to string exception handling function prototype numeric mixed scalar


Since the look of the code inside and some engineering needs to involve some MATLAB mixed programming, always want to see, the first one is to use C to write code, compiled by MATLAB call, which need to use the MEX function, A MEX program is a Dll,mex file written in accordance with a certain interface Specification (MTLAB), which can be either C or FORTRAN. This article is about writing in C.

In this case, if there is a loop in the code, the use of MATLAB will need to iterate over multiple times, and the C language compiled into a DLL, the first can put the loop body into a binary program, using MATLAB to speed up operations, rather than circular interpretation of the implementation of MATLAB code. There is also the use of C can speed up the development of code efficiency.

Set the compiler path in the MATLAB command window type Mex-setup, as long as you follow the prompts step by step setup. To test whether your path is set correctly, save the following program as HELLO.C.

#include "mex.h"
void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
{
   mexprintf (" Hello,world!\n ");
}

Suppose you put hello.c under the C:\TEST\, in MATLAB with the CD C:\TEST\ the current directory is changed to C:\TEST\ (note that it is useless to add only C:\TEST\ to the search path). Now knock:
Mex HELLO.C
If all goes well, the compilation should exit normally after the compiler prompts the message. If you have added C:\TEST\ to the search path and now type Hello, the program will hit a line on the screen: hello,world! Look at the c\test\ directory and you'll find one more file: HELLO.DLL. Description of the MEX function has been completed, compilation successful interface function specification mexfunction introduction void mexfunction (int nlhs, Mxarray *plhs[], int nrhs, const mxarray *prhs[])
NLHS: Number of output parameters
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, respectively.
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 give different screen outputs depending on the input parameter changes:
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[]) c3/>{ 
int *i; 
I=MXGETPR (Prhs[0]); PRHS is an array of pointers (each of which is a pointer), so return a pointer
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 it cannot be computed if we do not know the exact size of the matrix.
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 MX Array *prhs[]) 
{ 
double *data; 
int m,n; 
int i,j; 
DATA=MXGETPR (Prhs[0]); Gets the pointer to the matrix 
M=mxgetm (prhs[0]);//Gets the number of rows of the Matrix 
N=mxgetn (prhs[0]);//Gets the number of columns for 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) 
  


There is also if the data is not two-dimensional, you can use the following function to obtain the number of dimensions of the data (vector: 1, Matrix: 2, ...) ) and the dimension group.
Gets the number of dimensions Numofdim = Mxgetnumberofdimensions (Parray); Get dimension Group Dims = Mxgetdimensions (Parray);
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 it is passed to the one-dimensional array data in 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 output the processed elements:
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. In addition, if it is not an output element, remember to release it after applying for memory: Mwsize *subscript;
Subscript = (Mwsize *) mxcalloc (Numofdim, sizeof (mwsize)); Mxfree (subscript);
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 MX 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. In addition, it should be noted that when the code suffix named. C, the variable must be declared at once, and placed at the front of the code, with the suffix. cpp. This problem does not occur.
List of commonly used MEX functions

MX Matrix Library

Mwindex (C and Fortran)

Type for index values

Mwpointer (Fortran)

Pointer Type for Platform

Mwsignedindex (C and Fortran)

Signed integer type for size values

mwsize (C and Fortran)

Type for size values

Mxaddfield (C and Fortran)

Field to structure array

Mxarray (C and Fortran)

Type for MATLAB Array

mxarraytostring (C)

Convert Array to string

Mxassert (C)

Check assertion value for debugging purposes

mxasserts (C)

Check assertion value without printing assertion text

Mxcalcsinglesubscript (C and Fortran)

Offset from first element to desired element

Mxcalloc (C and Fortran)

Allocate dynamic memory for array using MATLAB memory Manager

Mxchar (C)

Type for string array

Mxclassid (C)

Enumerated value identifying class of array

mxclassidfromclassname (Fortran)

Identifier corresponding to Class

mxcomplexity (C)

Flag specifying whether array have imaginary components

mxcopycharactertoptr (Fortran)

CHARACTER values from Fortran array to pointer array

mxcopycomplex16toptr (Fortran)

Complex*16 values from Fortran array to pointer array

mxcopycomplex8toptr (Fortran)

Complex*8 values from Fortran array to pointer array

mxcopyinteger1toptr (Fortran)

Integer*1 values from Fortran array to pointer array

mxcopyinteger2toptr (Fortran)

Integer*2 values from Fortran array to pointer array

mxcopyinteger4toptr (Fortran)

Integer*4 values from Fortran array to pointer array

Mxcopyptrtocharacter (Fortran)

CHARACTER values from pointer array to Fortran array

mxCopyPtrToComplex16 (Fortran)

COMPLEX*16 values from pointer array to Fortran array

mxCopyPtrToComplex8 (Fortran)

Complex*8 values from pointer array to Fortran array

mxCopyPtrToInteger1 (Fortran)

Integer*1 values from pointer array to Fortran array

MxCopyPtrToInteger2 (Fortran)

Integer*2 values from pointer array to Fortran array

mxCopyPtrToInteger4 (Fortran)

Integer*4 values from pointer array to Fortran array

Mxcopyptrtoptrarray (Fortran)

Pointer values from Pointer array to Fortran array

MxCopyPtrToReal4 (Fortran)

Real*4 values from pointer array to Fortran array

MxCopyPtrToReal8 (Fortran)

Real*8 values from pointer array to Fortran array

mxcopyreal4toptr (Fortran)

Real*4 values from Fortran array to pointer array

mxcopyreal8toptr (Fortran)

Real*8 values from Fortran array to pointer array

Mxcreatecellarray (C and Fortran)

unpopulated n-d Cell Array

Mxcreatecellmatrix (C and Fortran)

unpopulated 2-d Cell Array

Mxcreatechararray (C and Fortran)

unpopulated n-d string array

mxcreatecharmatrixfromstrings (C and Fortran)

Create populated 2-d string array

Mxcreatedoublematrix (C and Fortran)

2-d, double-precision, floating-point array initialized to 0

mxcreatedoublescalar (C and Fortran)

Scalar, double-precision array initialized to specified value

Mxcreatelogicalarray (C)

n-d logical array initialized to False

Mxcreatelogicalmatrix (C)

2-d, logical array initialized to False

mxcreatelogicalscalar (C)

Scalar, logical array

Mxcreatenumericarray (C and Fortran)

unpopulated n-d Numeric Array

Mxcreatenumericmatrix (C and Fortran)

Numeric matrix initialized to 0

Mxcreatesparse (C and Fortran)

2-d unpopulated Sparse Array

Mxcreatesparselogicalmatrix (C)

unpopulated 2-d, sparse, logical array

mxcreatestring (C and Fortran)

Create 1-by-n array initialized to specified string

Mxcreatestructarray (C and Fortran)

unpopulated n-d Structure Array

Mxcreatestructmatrix (C and Fortran)

unpopulated 2-d Structure Array

Mxdestroyarray (C and Fortran)

Free dynamic memory allocated by mxcreate* functions

Mxduplicatearray (C and Fortran)

Make deep copy of array

Mxfree (C and Fortran)

Free dynamic memory allocated by Mxcalloc, Mxmalloc, or Mxrealloc functions

Mxgetcell (C and Fortran)

Contents of array cell

mxgetchars (C)

Pointer to character array data

Mxgetclassid (C and Fortran)

Class of Array

Mxgetclassname (C and Fortran)

Class of array As String

Mxgetdata (C and Fortran)

Pointer to Real data

mxgetdimensions (C and Fortran)

Pointer to Dimensions array

mxgetelementsize (C and Fortran)

Number of bytes required to store each data element

mxgeteps (C and Fortran)

Value of EPS

Mxgetfield (C and Fortran)

field value, given field name and index, into structure array

Mxgetfieldbynumber (C and Fortran)

field value, given field number and index, into structure array

Mxgetfieldnamebynumber (C and Fortran)

Field name, given field number, in structure array

Mxgetfieldnumber (C and Fortran)

Field number, given field name, in structure array

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.