ConverterNICEToMatlab.cpp 2.4 KB

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