jump to navigation

A very brief introduction to C implementation in Matlab August 23, 2009

Posted by viboon in : C, Matlab , add a comment

1. Create a file in C format which a heading file of mex.h has to be added in order to interface with Matlab. Instead of staring from main() function, we use mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) to acquire and return the variables between C function and Matlab.

#include "math.h"
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
    //Declare the input variable in pointer format
    mxArray *xInput;
    double *xMat, *xAns;
    int row, col;
    //Copy to the pointer
    xInput = prhs[0];
    //Get the matrix
    xMat = mxGetPr(xInput);
    row = mxGetM(xInput);
    col = mxGetN(xInput);
    //Allocate the memory for output value
    plhs[0] = mxCreateDoubleMatrix(row, col, mxREAL);
    //Apply the pointer to the reserved memory
    xAns = mxGetPr(plhs[0]);
    //Start your coding here

2. Compile the C file by using a command below:

mex mycfun.c

3. Call your compiled C function in the M-file.

[xAns] = mycfun(xInput);

4. Enjoy!

Tags: , , , ,

Related posts:

Writing C functions in Matlab August 17, 2009

Posted by viboon in : C, Matlab , add a comment

I face a long computing time problem when I work on Matlab to compute the large and complicated matrices with many loops inside. To reduce the calculating time particularly the loops, the external function written in C language is an effective method to be applied in the MEX-file format. By implementing C function, the computing time can be faster significantly.

Good how-to sources:
- MathWorks: Calling C and Fortran Programs from MATLAB Command Line
- Writing C Functions in MATLAB (MEX-Files)

Tags: , , , ,

Related posts:

How to compile C/C++ using GNU compiler in Linux July 25, 2009

Posted by viboon in : C, Ubuntu , add a comment

To display the installed GNU compiler version

$ gcc -v

Compile the code

$ gcc test.c

Using this command the compiler will make an output file named “a.out”. In order to change it to the different name, an additional argument has to be added.

$ gcc -o outputoftest test.c

To run the compiled program when the current directory is not included in the environmental variable.

$ ./outputoftest

Tags: , , , , ,

Related posts: