From: Ehsan Salari on
"James Tursa" <aclassyguy_with_a_k_not_a_c(a)hotmail.com> wrote in message <hr7s00$k8c$1(a)fred.mathworks.com>...
> "Ehsan Salari" <ehsan.salari(a)gmail.com> wrote in message <hr7p0c$b02$1(a)fred.mathworks.com>...
> > Hello,
> >
> > I am trying to read a 2D array ("aper") from a mat file in C++ (Visual Studio) and assign it to a 2D array ("aper1"). I am using the following code:
> >
> > MATFile *pmat;
> > mxArray *pa1;
> > int ** aper1;
> > aper = new int*[nbixel];
> > for (int i = 0; i < nbixel; i++)
> > {
> > aper[i] = new int[3];
> > }
> > //////////
> > pmat = matOpen(filename.c_str(), "r");
> > pa1 = matGetVariable(pmat, "aper");
> > aper1 = (int**)mxGetData(pa1);
> > mxDestroyArray(pa1);
> > matClose(pmat);
> >
> > I can read the variable "aper" but I cannot assign it to aper1. Could you please let me know how I can read a 2D array in C++? In particular, can I use mxGetData in case of a 2D array?
> >
> > Thanks!
>
> You need to copy each and every element *individually*. So you need to do this:
>
> int *pr; // assuming the variable in the mat file is an int32 class variable
> :
> pr = mxGetData(pa1);
> for( etc. )
> for( etc. )
> aper1[i][j] = pr[etc.]
>
> You can fill in the details of the loops based on the size of pa1.
>
> You might also consider foregoing your 2D array in C and just go with a 1D array with linear indexing. Often this is easier to manage in your code.
>
> James Tursa

Thanks a lot James! So pa1 should be treated is a 1 Dimensional array, but when I do this and I want to get pr[0] it gives me access violation error. I am not sure why.

Ehsan