Advertisement
celestialgod

Reassign with index (C++ file)

May 28th, 2015
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.20 KB | None | 0 0
  1. /* indexAssign_inplace.cpp */
  2. #include "mex.h"
  3. #include "matrix.h"
  4. extern "C" int mxUnshareArray(mxArray *array_ptr, int level);
  5.  
  6. void modifyArrayByIndex(mxArray *inarr, const mxArray *inarr2, const mxArray *idxarr){
  7.     size_t rowNum = mxGetM(inarr);
  8.     size_t colNum = mxGetN(inarr);
  9.     if (mxGetM(inarr2)!=rowNum || mxGetN(inarr2)!=colNum)
  10.         mexErrMsgTxt("The dimensions of first two inputs must be equal.");
  11.    
  12.     double* pArr_A = (double*) mxGetPr(inarr);
  13.     double* pArr_B = (double*) mxGetPr(inarr2);
  14.     double* pVec_idx = (double*) mxGetPr(idxarr);
  15.     size_t idxLength = mxGetNumberOfElements(idxarr);
  16.    
  17.     for (int i = 1; i < (int) idxLength; i++)
  18.     {
  19.         for (int j = 0; j < i; j++)
  20.         {
  21.             int index = ((int) pVec_idx[j] - 1) * rowNum + (int) pVec_idx[i] - 1;
  22.             pArr_A[index] = pArr_B[index];
  23.         }
  24.     }
  25. }
  26.  
  27. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  28. {
  29.     // input: prhs = [A, B, idx]
  30.     if (nrhs != 3)
  31.         mexErrMsgTxt("Input is not enough.");
  32.     plhs[0] = (mxArray*) prhs[0];
  33.     mxUnshareArray(plhs[0], true);
  34.     modifyArrayByIndex(plhs[0], prhs[1], prhs[2]);
  35. }
  36.  
  37. /* indexAssign.cpp */
  38. #include "mex.h"
  39. #include "matrix.h"
  40.  
  41. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
  42. {
  43.     // input: prhs = [A, B, idx]
  44.     if (nrhs != 3)
  45.         mexErrMsgTxt("Input is not enough.");
  46.  
  47.     size_t rowNum = mxGetM(prhs[0]);
  48.     size_t colNum = mxGetN(prhs[0]);
  49.     if (mxGetM(prhs[1])!=rowNum || mxGetN(prhs[1])!=colNum)
  50.         mexErrMsgTxt("The dimensions of first two inputs must be equal.");
  51.    
  52.    
  53.     double* pArr_A = (double*) mxGetPr(prhs[0]);
  54.     double* pArr_B = (double*) mxGetPr(prhs[1]);
  55.     double* pVec_idx = (double*) mxGetPr(prhs[2]);
  56.     size_t idxLength = mxGetNumberOfElements(prhs[2]);
  57.    
  58.     plhs[0] = mxDuplicateArray(prhs[0]);
  59.     double* pOutputArr = (double*) mxGetPr(plhs[0]);
  60.     for (int i = 1; i < (int) idxLength; i++)
  61.     {
  62.         for (int j = 0; j < i; j++)
  63.         {
  64.             int index = ((int) pVec_idx[j] - 1) * rowNum + (int) pVec_idx[i] - 1;
  65.             pOutputArr[index] = pArr_B[index];
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement