Pass Scalar Values in C MEX File
Pass Scalar as Matrix
This example shows how to write a MEX file that passes scalar values.
Suppose that you have the following C code, timestwo
, that
takes a scalar input, a 1
-by-1
matrix, and
doubles it.
void timestwo(double y[], double x[]) { y[0] = 2.0*x[0]; return; }
C Code Analysis
To see the function written as a MEX file, open timestwo.c
in the MATLAB® Editor.
In C/C++, the compiler checks function arguments for number and type. However, in MATLAB, you can pass any number or type of arguments to a function; the function is responsible for argument checking. MEX files also allow variable inputs. Your MEX file must safely handle any number of input or output arguments of any supported type.
This code checks for the proper number of arguments.
if(nrhs != 1) { mexErrMsgIdAndTxt( "MATLAB:timestwo:invalidNumInputs", "One input required."); } else if(nlhs>1) { mexErrMsgIdAndTxt( "MATLAB:timestwo:maxlhs", "Too many output arguments."); }
This code checks if the input is a real, scalar double value.
mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows==1 && ncols==1) ) { mexErrMsgIdAndTxt( "MATLAB:timestwo:inputNotRealScalarDouble", "Input must be a noncomplex scalar double."); }
Build and Test Example
Build the MEX file.
mex -v -R2018a timestwo.c
Call the function.
x = 2; y = timestwo(x)
y = 4
Pass Scalar by Value
This example shows how to write a MEX file that passes a scalar by value.
The mxGetScalar
function returns the value of a scalar
instead of a pointer to a copy of the scalar variable,
x
.
The following C code implements the timestwo_alt
function.
void timestwo_alt(double *y, double x) { *y = 2.0*x; }
Compare the timestwo_alt
function signature with the
timestwo
function signature.
void timestwo_alt(double *y, double x)
void timestwo(double y[], double x[])
The input value x
is a scalar of type
double
. In the timestwo
function,
the input value is a matrix of type double
.
To see the function written as a MEX file, open timestwoalt.c
in the MATLAB Editor.
Compare the call to timestwo_alt
to the call to
timestwo
.
/* Get the scalar value of the input x */ /* note: mxGetScalar returns a value, not a pointer */ x = mxGetScalar(prhs[0]); /* Assign a pointer to the output */ y = mxGetDoubles(plhs[0]); /* Call the timestwo_alt subroutine */ timestwo_alt(y,x);
/* Assign pointers to each input and output. */ x = mxGetDoubles(prhs[0]); y = mxGetDoubles(plhs[0]); /* Call the timestwo subroutine. */ timestwo(y,x);
The value x
created by mxGetScalar
is a scalar not a pointer.