timestwo.c
#include "mex.h"
void timestwo (double y[ ], double x[ ], int i)
{
int j;
for (j = 0; j < i; j++)
y[ j ] = 2.0 * x[ j ];
}
void mexFunction (int nlhs, mxArray *plhs[ ], int nrhs,const mxArray, *prhs[ ])
{
double *x, *y;
int mrows, ncols;
/* The input must be a noncomplex scalar double */
mrows = mxGetM (prhs[ 0 ]);
ncols = mxGetN (prhs[ 0 ]);
/* Create matrix for the return argument */
plhs[ 0 ] = mxCreateDoubleMatrix (mrows, ncols, mxREAL);
/* Assign pointers to each input and output */
x = mxGetPr (prhs[ 0 ]);
y = mxGetPr (plhs[ 0 ]);
/* Call the timestwo subroutine */
timestwo (y, x, ncols);
}
Here's how you'd compile and run it:
» mex timestwo.c
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 11.00.7022 for 80x86
Copyright (C) Microsoft Corp 1984-1997. All rights reserved.
» timestwo(7)
ans =
14
» timestwo([7, 3])
ans =
14 6
Explaining "timestwo.c"
The C-MEX function "timestwo" has the following pseudo-code:
#include "mex.h"
void timestwo (double output_vector, double input_vector, int length_of_input_vector)
{
output_vector = input_vector * 2
}
void mexFunction (int nlhs, mxArray *plhs[ ], int nrhs,const mxArray, *prhs[ ] )
{
double *x, *y;
int mrows, ncols;
/* Get the dimensions of input matrix */
mrows = number of rows in input matrix
ncols = number of columns in input matrix
/* Create matrix to hold the output */
plhs[ 0 ] = a real, double matrix of size mrows x ncols
/* Assign pointers to each input and output */
x = pointer_to_input
y = pointer_to_output
/* Call the timestwo subroutine */
timestwo (y, x, ncols);
}