ConverterNICEToMatlab.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifdef NICE_USELIB_MEX
  2. #include "ConverterNICEToMatlab.h"
  3. using namespace NICE;
  4. using namespace NICE::MatlabConversion;
  5. // b_adaptIndexCtoM: if true, dim k will be inserted as k, not as k+1 (which would be the default for C->M)
  6. mxArray* MatlabConversion::convertSparseVectorFromNice( const NICE::SparseVector & niceSvec, const bool & b_adaptIndexCtoM )
  7. {
  8. mxArray * matlabSparseVec = mxCreateSparse( niceSvec.getDim() /*m*/, 1/*n*/, niceSvec.size()/*nzmax*/, mxREAL);
  9. // To make the returned sparse mxArray useful, you must initialize the pr, ir, jc, and (if it exists) pi arrays.
  10. // mxCreateSparse allocates space for:
  11. //
  12. // A pr array of length nzmax.
  13. // A pi array of length nzmax, but only if ComplexFlag is mxCOMPLEX in C (1 in Fortran).
  14. // An ir array of length nzmax.
  15. // A jc array of length n+1.
  16. double* prPtr = mxGetPr(matlabSparseVec);
  17. mwIndex * ir = mxGetIr( matlabSparseVec );
  18. mwIndex * jc = mxGetJc( matlabSparseVec );
  19. jc[1] = niceSvec.size(); jc[0] = 0;
  20. mwSize cnt = 0;
  21. for ( NICE::SparseVector::const_iterator myIt = niceSvec.begin(); myIt != niceSvec.end(); myIt++, cnt++ )
  22. {
  23. // set index
  24. if ( b_adaptIndexCtoM )
  25. ir[cnt] = myIt->first-1;
  26. else
  27. ir[cnt] = myIt->first;
  28. // set value
  29. prPtr[cnt] = myIt->second;
  30. }
  31. return matlabSparseVec;
  32. }
  33. mxArray* MatlabConversion::convertMatrixFromNice( const NICE::Matrix & niceMatrix )
  34. {
  35. mxArray *matlabMatrix = mxCreateDoubleMatrix( niceMatrix.rows(), niceMatrix.cols(), mxREAL );
  36. double* matlabMatrixPtr = mxGetPr( matlabMatrix );
  37. for( int i = 0; i < niceMatrix.rows(); i++ )
  38. {
  39. for( int j = 0; j < niceMatrix.cols(); j++ )
  40. {
  41. matlabMatrixPtr[i + j*niceMatrix.rows()] = niceMatrix(i,j);
  42. }
  43. }
  44. return matlabMatrix;
  45. }
  46. mxArray* MatlabConversion::convertVectorFromNice( const NICE::Vector & niceVector )
  47. {
  48. mxArray *matlabVector = mxCreateDoubleMatrix( niceVector.size(), 1, mxREAL );
  49. double* matlabVectorPtr = mxGetPr( matlabVector );
  50. for( int i = 0; i < niceVector.size(); i++ )
  51. {
  52. matlabVectorPtr[i] = niceVector[i];
  53. }
  54. return matlabVector;
  55. }
  56. #endif