我试图弄清楚如何从 mex 函数访问存储在 matlab 结构中的字段中的矩阵。
太啰嗦了……让我解释一下:
我有一个 matlab 结构,其定义如下:
matrixStruct = struct('matrix', {4, 4, 4; 5, 5, 5; 6, 6 ,6})
我有一个 mex 函数,我希望能够在其中接收指向矩阵中第一个元素的指针(矩阵 [0] [0],用 c 术语表示),但我一直无法弄清楚该怎么做那。
我尝试了以下方法:
/* 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)));
}
最终打印的内容如下:
4.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
我还尝试了以下变体,认为嵌套函数调用可能有些不稳定,但无济于事:
/* 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 */
有没有人知道我如何才能实现我想要的目标,或者我可能做错了什么?
谢谢!
编辑:根据 yuk 的评论,我尝试对一个结构进行类似的操作,该结构有一个名为 array 的字段,它是一个一维双精度数组。
包含数组的结构定义如下:
arrayStruct = struct('array', {4.44, 5.55, 6.66})
我在 mex 函数中对 arrayStruct 尝试了以下操作:
mptr = mxGetPr(mxGetField(prhs[0], 0, "array"));
printf("%f\n", *(mptr));
printf("%f\n", *(mptr + 1));
printf("%f\n", *(mptr + 2));
...但输出遵循之前打印的内容:
4.440000
0.000000
0.000000