/* Example code for converting between C++ vector<vector<double>> and mxArray
*
* Because C++ memory is row ordered and MATLAB mxArray memory is column
* ordered, the conversion is done in both directions as the transpose so
* that the memory copies are done as entire rows/colums.
*
* Programmer: James Tursa
*/
/* Includes ----------------------------------------------------------- */
#include "mex.h"
#include <vector>
using namespace std;
// Convert a C++ matrix to an mxArray as the TRANSPOSE
mxArray *vv2mx(vector<vector<double>> mat)
{
size_t rows = mat.size();
size_t cols = mat[0].size();
mxArray *T = mxCreateDoubleMatrix(cols, rows, mxREAL);
double *in_buf = (double *) mxGetData(T);
for (int i = 0; i<rows; i++) {
memcpy( in_buf + i * cols, &mat[i][0], cols *sizeof(double) );
}
return T;
}
// Convert an mxArray to a C++ matrix as the TRANSPOSE
vector<vector<double>> mx2vv(const mxArray *T) {
size_t rows = mxGetN(T);
size_t cols = mxGetM(T);
double *in_buf = (double *) mxGetData(T);
vector<vector<double>> mat(rows, vector<double>(cols));
for (int i = 0; i<rows; i++) {
memcpy( &mat[i][0], in_buf + i * cols, cols *sizeof(double) );
}
return mat;
}
// Display a C++ matrix
void vvdisp(vector<vector<double>> mat)
{
size_t rows = mat.size();
size_t cols = mat[0].size();
for (int i = 0; i<rows; i++) {
for( int j=0; j<cols; j++ ) {
mexPrintf("%f ",mat[i][j]);
}
mexPrintf("\n");
}
return;
}
// Display an mxArray
void mxdisp(const mxArray *T)
{
size_t rows = mxGetM(T);
size_t cols = mxGetN(T);
double *in_buf = (double *) mxGetData(T);
for (int i = 0; i<rows; i++) {
for( int j=0; j<cols; j++ ) {
mexPrintf("%f ",*(in_buf + i + j*rows));
}
mexPrintf("\n");
}
return;
}
/* Gateway ------------------------------------------------------------ */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
if( nrhs == 0 || !mxIsDouble(prhs[0]) || mxIsSparse(prhs[0]) || mxIsComplex(prhs[0]) ) {
mexErrMsgTxt("Need exactly one full double matrix input");
}
if( nlhs > 1 ) {
mexErrMsgTxt("Too many outputs.");
}
mexPrintf("\nInput matrix:\n");
mxdisp(prhs[0]);
mexPrintf("\nInput matrix as vv:\n");
vector<vector<double>> mat = mx2vv(prhs[0]);
vvdisp(mat);
mexPrintf("\n2*vv:\n");
size_t rows = mat.size();
size_t cols = mat[0].size();
for (int i = 0; i<rows; i++) {
for( int j=0; j<cols; j++ ) {
mat[i][j] *= 2.0;
}
}
vvdisp(mat);
mexPrintf("\nOutput matrix:\n");
plhs[0] = vv2mx(mat);
mxdisp(plhs[0]);
}
Best Answer