Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: Segmentation violation due to MEX code
Date: Tue, 7 Jul 2009 05:29:02 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 89
Message-ID: <h2umeu$ioi$1@fred.mathworks.com>
References: <h2tkfd$l84$1@fred.mathworks.com> <5b6d0b68-60e9-41be-a22f-ea755e2db20d@r33g2000yqn.googlegroups.com> <b3f3c949-95f6-4961-954a-eae386f6db10@24g2000yqm.googlegroups.com>
Reply-To: "Bruno Luong" <b.luong@fogale.findmycountry>
NNTP-Posting-Host: webapp-03-blr.mathworks.com
Content-Type: text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding: 8bit
X-Trace: fred.mathworks.com 1246944542 19218 172.30.248.38 (7 Jul 2009 05:29:02 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Tue, 7 Jul 2009 05:29:02 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:553291


> 
> What speed-ups do you achieve after these
> modifications?

Elapsed time is 2.187960 seconds. % <- ACCUMARRAY
Elapsed time is 3.918172 seconds. % <- MEX, MSVS 6.0, compiled with -O

codes attached bellow.

% Bruno


function timethem

N=700*600*20;
x = rand(1,N);
e = rand(1,N);
y = floor(rand(1,N)*255);

tic
v = x.*e;
yp1 = y(:)+1;
S = accumarray(yp1,v(:))./accumarray(yp1,1,[],[],1);
toc
clear S

tic
S =  Calculate_I_Values(e(:), x(:), y(:));
toc
clear S

end


/*
 * Calculate_I_Values.c
 * Used to speed up the I mapping calculations
 *
 * This is a MEX-file for MATLAB.
 */

#include "mex.h"
#include "matrix.h"

/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[]) {
    /* variable declarations here */
    double *e, *x, *y, *I;
    int eRows, eCols, xRows, xCols, yRows, yCols, index, ySize;
    int m, i, j;
    double num, den;
    
    e = mxGetPr(prhs[0]);
    eRows = mxGetN(prhs[0]);
    eCols = mxGetM(prhs[0]);
    
    x = mxGetPr(prhs[1]);
    xRows = mxGetN(prhs[1]);
    xCols = mxGetM(prhs[1]);
    
    y = mxGetPr(prhs[2]);
    yRows = mxGetN(prhs[2]);
    yCols = mxGetM(prhs[2]);
    ySize = mxGetNumberOfElements(prhs[2]);
    
    
    /* Allocate output memory */
    plhs[0] = mxCreateDoubleMatrix(1, 256, mxREAL);
    I = mxGetPr(plhs[0]);
    
    /* code here */    
    for (m = 0; m <= 255; ++m) {
        num = 0;
        den = 0;
        for (i = 0; i < yRows; ++i)
            for (j = 0; j < yCols; ++j) {
            index = i * yCols + j;
            if (m == y[index]) {
                num += x[i];
                ++den;
            }
        }
        num *= e[j];
        if (den != 0) I[m] = num / den;
        else I[m] = num;
    }
    
}