我试图找出如何从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的评论,我尝试对一个结构进行类似的操作,该结构有一个叫做数组的字段,它是一维的双精度数组 .
包含数组的结构定义如下:
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
3 回答
我经历过这个:我有一个带有字段的结构,它是一个矩阵 . 在C中,相应的结构例如是
double**
. 尝试使用engGetVariable(engine,MyStruct.theField)
访问该字段失败 . 我使用temp变量来存储MyStruct.theField
,然后使用engGetVariable(engine, tempVar)
,代码 to get the matrix field from the struct 看起来像那样非常相似 to set the matrix field to the struct 我这样做了
struct('field', {a b c})
是结构构造函数的一种特殊形式,它创建一个与单元格数组大小相同的结构数组,将单元格的每个元素放入结构的相应元素的字段'field'中 . 就是这样:产生与此相同的结果:
您的问题的解决方案是使用方括号来形成常规(非单元格)数组,如下所示:
您正在尝试访问MATLAB中的单元格数组变量 . 您确定数据是否存储了?如果你把双数组放入结构中会发生什么?
我认为问题是MATLAB如何将数据存储在单元阵列中 . 试着运行这个:
输出:
您可以看到单元格数组的每个元素占用额外的60个字节到数字大小 .