|
To OP:
First I need to chastise you for your nomenclature. In general, when a reviewer such as myself reads code that involves matrices and there are indexes i and j used, I expect i to be used for rows and j to be used for columns. You did the reverse. Second, when there is a function involved that takes a row and a column argument, it is expected that the row is listed first and the column second. You did the reverse. This makes it extremely annoying to read and debug your code. Every time I read a line I have to stop my brain from doing what it naturally wants to do with i and j and force it to think backwards. Same with the function calls. Please, in the future, use i for rows and j for columns and list function arguments in row,column order.
Now that my rant is done, back to the original problem ...
Your use of digitalVal for indexing does not match the m-file version, and your use of coord for imageOut does not use the correct number of rows for that matrix and misuses digitalVal in the call. Here is a mex routine that reproduces these lines of m-code:
m-code:
-----------------
[imHeight imWidth] = size(I);
dots = zeros(255, imWidth);
for i = 1:imWidth
for j = 1:imHeight
val = I(j,i);
dots(val, i) = dots(val, i) + val;
end
end
mex code:
----------------------
#include "stdafx.h"
#include "mex.h"
#include "math.h"
int coord(int i, int j, int m)
{
return i * m + j;
}
// The gateway routine
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Create a pointer to the input image matrix
double *imageIn = mxGetPr(prhs[0]);
// Get the dimensions of the input image matrix
int m = mxGetM(prhs[0]);
int n = mxGetN(prhs[0]);
// Create the pointer to the output waveform image matrix
plhs[0] = mxCreateDoubleMatrix(255, n, mxREAL);
double *imageOut = mxGetPr(plhs[0]);
// Nested loop
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
double doubleVal = imageIn[coord(i,j,m)];
int digitalVal = ((int) doubleVal) - 1;
imageOut[coord(i,digitalVal,255)] += doubleVal;
}
}
}
Finally, I would like to point out when mex routines are useful for speed improvements and when they are not. If there is a lot of intermediate variable creation within your loop, then a mex routine can often avoid that overhead and give you a speed improvement. Or if there are a lot of array slices used in the loop (where MATLAB has to do a data copy to create the slice), then a mex routine can often access the slice directly without a data copy and run quite a bit faster. Those are the two main sources of speed improvements when converting m-code to C code. I didn't time the above mex code against the m-code, but it doesn't appear to have either of the two speedups that I mentioned to any great degree, so I would not necessarily expect it to run much faster than the m-code.
James Tursa
|