Path: news.mathworks.com!not-for-mail
From: "Bruno Luong" <b.luong@fogale.findmycountry>
Newsgroups: comp.soft-sys.matlab
Subject: Re: help regarding 2D matrix using c mex file
Date: Thu, 20 Aug 2009 09:18:18 +0000 (UTC)
Organization: FOGALE nanotech
Lines: 53
Message-ID: <h6j4cq$5ll$1@fred.mathworks.com>
References: <h6b2k6$oh2$1@fred.mathworks.com> <h6b3nq$6ft$1@fred.mathworks.com> <h6dsve$37p$1@fred.mathworks.com> <h6et12$284$1@fred.mathworks.com> <h6fhbo$l34$1@fred.mathworks.com> <h6gav1$hjm$1@fred.mathworks.com> <h6j26v$n34$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 1250759898 5813 172.30.248.38 (20 Aug 2009 09:18:18 GMT)
X-Complaints-To: news@mathworks.com
NNTP-Posting-Date: Thu, 20 Aug 2009 09:18:18 +0000 (UTC)
X-Newsreader: MATLAB Central Newsreader 390839
Xref: news.mathworks.com comp.soft-sys.matlab:564696


"oruganti murthy" <omurthy@yahoo.com> wrote in message <h6j26v$n34$1@fred.mathworks.com>...
> Dear James,
> Thank you very much for your detailed steps. 
> I have made the changes and here is the output I obtained.
> I actually wanted my output (for some later computations in C) the *output to be format output[][]. How can I obtain that?

C-2D are pointer array (level1) of pointers (level2); each of the pointer (level2) is 1D array.

So if you want to convert Matlab linear indexing array to C 2D-array you need to do the following.

- Allocate an array of pointers (level1) of the length equal to the number of (Matlab) columns in the data.
- Assign the value of each jth pointer element (level2) as the address of the first element of column #j.

After using it, don't forget to free the array level1.

Remember, C and Matlab arrays are transposed to each other.

Try this:

% On Matlab command line:

mex c2d.c
c2d([1 2 3; 4 5 6]);

/* Mex test program c2d.c */
#include "mex.h"

void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])
{
    double **Carray; 
    double *data;
    mwSize m, n, i, j;
    
    data = mxGetPr(prhs[0]);
    m = mxGetM(prhs[0]);
    n = mxGetN(prhs[0]);
    
    /* Create C 2D array */
    Carray = mxCalloc(n, sizeof(double*));
    for (j=0; j<n; j++)
        Carray[j] = data+m*j;
    
    /* Use it */
    for (i=0; i<m; i++)
        for (j=0; j<n; j++)
            mexPrintf("data(%i,%i) = %f\n", i+1, j+1, Carray[j][i]);
   
    mxFree(Carray);
    
    return;
}

/* Bruno