As it turns out, incorporating CUDA code in MATLAB can be easily done! 🙂
MATLAB provides functionality for loading arbitrary dynamic libraries and invoking their functions. This is especially easy for invoking C/C++ code in a MATLAB program. Such functionality is possible using the so called MEX functions.
Mex functions can be created with the mex command in MATLAB. Essentially, mex takes as input a C/C++ source file, invokes the default C/C++ compiler installed in the operating system (GCC or CL), and creates a mexa64 file (on a 64-bit machine) which can be used like any other MATLAB function.
The C/C++ file that is passed to mex must have the following included in it:
#include "mex.h" // The mex header containing the necessary interop definitions
* The "gateway" function which is the entry point for the MATLAB
* function call (will be executed when the mex file is invoked in
void mexFunction(int nlhs, mxArray *plhs,
int nrhs, const mxArray *prhs)
The arguments that are passed from MATLAB are accessible using the prhs parameter (which stands for parameters-right hand side). Any output that the gateway function generates can be returned using the plhs parameter (which stands for parameter-left hand side). The number of the arguments that are passed to the gateway function is stored in the nrhs parameter and the number of outputs that the MATLAB code expects from the gateway function is stored in the nlhs parameter. From this point on, I refer to the file containing the above code as the mex gateway file. Also, I will refer to the mexFunction above as the gateway function.