How to access a matrix in a matlab struct's field from a mex function?
Posted
by B. Ruschill
on Stack Overflow
See other posts from Stack Overflow
or by B. Ruschill
Published on 2010-05-11T18:51:58Z
Indexed on
2010/05/12
1:04 UTC
Read the original article
Hit count: 278
I'm trying to figure out how to access a matrix that is stored in a field in a matlab structure from a mex function.
That's awfully long winded... Let me explain:
I have a matlab struct that was defined like the following:
matrixStruct = struct('matrix', {4, 4, 4; 5, 5, 5; 6, 6 ,6})
I have a mex function in which I would like to be able to receive a pointer to the first element in the matrix (matrix[0][0], in c terms), but I've been unable to figure out how to do that.
I have tried the following:
/* Pointer to the first element in the matrix (supposedly)... */
double *ptr = mxGetPr(mxGetField(prhs[0], 0, "matrix");
/* Incrementing the pointer to access all values in the matrix */
for(i = 0; i < 3; i++){
printf("%f\n", *(ptr + (i * 3)));
printf("%f\n", *(ptr + 1 + (i * 3)));
printf("%f\n", *(ptr + 2 + (i * 3)));
}
What this ends up printing is the following:
4.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
I have also tried variations of the following, thinking that perhaps it was something wonky with nested function calls, but to no avail:
/* Pointer to the first location of the mxArray */
mxArray *fieldValuePtr = mxGetField(prhs[0], 0, "matrix");
/* Get the double pointer to the first location in the matrix */
double *ptr = mxGetPr(fieldValuePtr);
/* Same for loop code here as written above */
Does anyone have an idea as to how I can achieve what I'm trying to, or what I am potentially doing wrong?
Thanks!
Edit: As per yuk's comment, I tried doing similar operations on a struct that has a field called array which is a one-dimensional array of doubles.
The struct containing the array is defined as follows:
arrayStruct = struct('array', {4.44, 5.55, 6.66})
I tried the following on the arrayStruct from within the mex function:
mptr = mxGetPr(mxGetField(prhs[0], 0, "array"));
printf("%f\n", *(mptr));
printf("%f\n", *(mptr + 1));
printf("%f\n", *(mptr + 2));
...but the output followed what was printed earlier:
4.440000
0.000000
0.000000
© Stack Overflow or respective owner