Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Inplace array (mex)
Date: Sat, 27 Jun 2009 12:41:01 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 71
Message-ID: <h2540t$73d$1@fred.mathworks.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 1246106461 7277 172.30.248.38 (27 Jun 2009 12:41:01 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Sat, 27 Jun 2009 12:41:01 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:551065


I want to create an inplace column vector using MEX. The idea is to create a column array that has its data pointer points on the the data block of an existing (input) matrix. Everything going well until I set the data pointer. Then it crashes 

a=rand(1,7)

a =

    0.8147    0.9058    0.1270    0.9134    0.6324    0.0975    0.2785

>> b=inplacecolumn(a,3)

Am I allowed to do such thing? If not what cause the crash?

Bruno

/* Here is my INPLACECOLUMN MEX function

/*************************************************************************
 * function b = inplacecolumn(a, k)
 * Return the inplace-column a(:,k)
 ************************************************************************/
#include "mex.h"
#include "matrix.h"

/* Gateway of inplacecolumn */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[]) {
    
    mwSize k, N, M;
    double *Pr;
    
    /* Check arguments */
    if (nrhs<2)
        mexErrMsgTxt("INPLACECOLUMN: Two input arguments required.");
    
    if (!mxIsNumeric(prhs[0]))
        mexErrMsgTxt("INPLACECOLUMN: First input LIST argument must be numeric.");
    
    if (!mxIsNumeric(prhs[1]))                              
        mexErrMsgTxt("INPLACECOLUMN: Second input K must be numeric.");

    M = mxGetM(prhs[0]);
    N = mxGetN(prhs[0]);
    
    /* Get the column number k */
    if (mxGetM(prhs[1])!=1 || mxGetN(prhs[1])!=1)
        mexErrMsgTxt("INPLACECOLUMN: Second input K must be a scalar.");
    
    if (mxGetClassID(prhs[1]) != mxDOUBLE_CLASS)
        mexErrMsgTxt("INPLACECOLUMN: Second input K must be a double.");
    
    k = (mwSize)(*mxGetPr(prhs[1]));
    if (k<1 || k>N)
        mexErrMsgTxt("INPLACECOLUMN: K is not valid.");
    
    /* Create the Matrix result (first output) */
    plhs[0] = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxREAL);
    Pr = mxGetPr(plhs[0]);
    mxFree(Pr);

    /* Set the dimension as one column */
    mxSetM(plhs[0], M);
    mxSetN(plhs[0], 1);
    
    /* Inplace data pointer */
    Pr = mxGetPr(prhs[0]);
    /* Ir crashes here when k>1 */
    mxSetPr(plhs[0], Pr+((k-1)*M));
      
    return;

} /* Gateway of INPLACECOLUMN.c */