Mex Code for Array Slicing
Ältere Kommentare anzeigen
Hello,
Thank you for your help.
I have a Matlab 3D array (buildSpaceGrid) 300 * 300 * 600. During my algorithm, i need to access subarrays of it several times. It is very inefficient to get such arrays with simple array slicing.
For example, i tried this, where build Space Grid is my 3D array, ixx,iyy, and izz are the starting x,y and z coordinates in the 3 dimensions.
buildSpaceGrid( ixx:ixx+partSize(1)-1,...
iyy:iyy+partSize(2)-1,...
izz:izz+partSize(3)-1)
It seems doing this type of array slicing is like death sentence in Matlab in terms of performance. I have to do this several times during my algorithm for different values of ixx, iyy and izz while my 3D array also updates as the algorithm progresses.
I decided to write a mex routine in c++ to make this more efficient. The routine takes the 3D array, buildSpaceGrid, ixx,iyy,izz and partsize and outputs the subarray.
#include "mex.h"
#include "matrix.h"
void mexFunction(
int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
mwSize nDimNum;
const mwSize *pSize;
bool *pD;
mxArray *Data;
bool *buildSpaceGrid;
int *ixx;
int *iyy;
int *izz;
mwSize i, j, k;
buildSpaceGrid = mxGetLogicals(prhs[0]);
ixx = (int *)mxGetPr(prhs[1]);
iyy = (int *)mxGetPr(prhs[1]);
izz = (int *)mxGetPr(prhs[3]);
pSize = (mwSize *)mxGetPr(prhs[4]);
nDimNum = mxGetNumberOfDimensions(prhs[0]);
plhs[0] = mxCreateLogicalArray(nDimNum, pSize);
pD = (bool *)mxGetData(plhs[0]);
for (i = 0; i < pSize[0]; i++) // NOT i=i !
{
for (j = 0; j < pSize[1]; j++)
{
for (k = 0; k < pSize[2]; k++)
{
pD[i+j*pSize[0]+k*(pSize[0]*pSize[1])] = buildSpaceGrid[ixx-1+i+(iyy-1+j)*pSize[0]+(izz-1+k)*(pSize[0]*pSize[1])];
}
}
}
}
I keep getting this wierd error when I try to compile it using mex command in Matlab.
error C2296: '*': illegal, left operand has type 'int *'
Can someone help me fix this problem.
I was also wondering if there is a better (effiient) way of improving the performance of this line of code.
Thank you so much for your help.
Akzeptierte Antwort
Weitere Antworten (1)
Maaz Saleem Kapadia
am 21 Dez. 2018
2 Kommentare
James Tursa
am 21 Dez. 2018
The only advice I can offer is what I had mentioned earlier. If you can move the downstream processing with that slice into the mex routine then you can avoid the up-front data copy which will save you some time. This may or may not be easy or feasible depending on what that downstream code actually does with the slice.
Maaz Saleem Kapadia
am 21 Dez. 2018
Kategorien
Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Hilfe-Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!