[37] | 1 | /* |
---|
| 2 | * INT_HIST(x, n) is a histogram of all integer values 1..n in x. |
---|
| 3 | * If n is not given, max(x) is used. |
---|
| 4 | */ |
---|
| 5 | #include "mex.h" |
---|
| 6 | #include "util.h" |
---|
| 7 | |
---|
| 8 | void mexFunction(int nlhs, mxArray *plhs[], |
---|
| 9 | int nrhs, const mxArray *prhs[]) |
---|
| 10 | { |
---|
| 11 | int rows, cols, len, i, bins; |
---|
| 12 | double *indata, *outdata; |
---|
| 13 | |
---|
| 14 | if((nrhs < 1) || (nrhs > 2)) |
---|
| 15 | mexErrMsgTxt("Usage: h = int_hist(x, n)"); |
---|
| 16 | |
---|
| 17 | /* prhs[0] is first argument. |
---|
| 18 | * mxGetPr returns double* (data, col-major) |
---|
| 19 | * mxGetM returns int (rows) |
---|
| 20 | * mxGetN returns int (cols) |
---|
| 21 | */ |
---|
| 22 | rows = mxGetM(prhs[0]); |
---|
| 23 | cols = mxGetN(prhs[0]); |
---|
| 24 | indata = mxGetPr(prhs[0]); |
---|
| 25 | len = rows*cols; |
---|
| 26 | |
---|
| 27 | if(mxIsSparse(prhs[0])) |
---|
| 28 | mexErrMsgTxt("Cannot handle sparse matrices. Sorry."); |
---|
| 29 | |
---|
| 30 | if(nrhs == 2) bins = *mxGetPr(prhs[1]); |
---|
| 31 | else { |
---|
| 32 | bins = indata[0]; |
---|
| 33 | for(i=0;i<len;i++) { |
---|
| 34 | if(indata[i] > bins) bins = indata[i]; |
---|
| 35 | } |
---|
| 36 | } |
---|
| 37 | |
---|
| 38 | /* plhs[0] is first output */ |
---|
| 39 | plhs[0] = mxCreateDoubleMatrix(1, bins, mxREAL); |
---|
| 40 | outdata = mxGetPr(plhs[0]); |
---|
| 41 | |
---|
| 42 | for(i=0;i<len;i++) { |
---|
| 43 | int v = (int)(*indata++) - 1; |
---|
| 44 | if((v < 0) || (v >= bins)) |
---|
| 45 | mexErrMsgTxt("value out of bounds"); |
---|
| 46 | outdata[v]++; |
---|
| 47 | } |
---|
| 48 | } |
---|
| 49 | |
---|