user1641496
user1641496

Reputation: 457

Reading matlab's mat file in C

I use the following mex code to get a variable from a mat file in C. The variable name is "T" and it is a 3D matrix.Then in matlab I assign the output of the mex to a matlab variable and all is well. The size of "T" is constant (230x329x105). Since I know the size, could I already in the mex code access elements of "T" by pointing to the correct index? Something like get me element [50][40][60], or do I have to remap the data in T to my own 3D array? Thanks.

mxArray* getTravelTimes(const char *file) {
MATFile *pmat;
const char *name;
mxArray *pa;

pmat = matOpen(file, "r");
if (pmat == NULL) {
printf("Error reopening file %s\n", file);
return(NULL);
}

pa = matGetNextVariable(pmat, &name);
if (pa == NULL) {
  printf("Error reading in file %s\n", file);
  return(NULL);
 } 

if (matClose(pmat) != 0) {
  printf("Error closing file %s\n",file);
  return(NULL);
}
return(pa);
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  mxArray* T;
  T = getTravelTimes("./traveltimes/T_p_01.mat");
  plhs[0] = T;
}

Upvotes: 3

Views: 1213

Answers (1)

kenm
kenm

Reputation: 23915

Use mxGetData on an mxArray to get a pointer to the first element of its real data. This is of type void *, so you will need to cast it to the correct data type before you can correctly do pointer arithmetic with it.

Upvotes: 1

Related Questions