我试图弄清楚如何从mex函数访问存储在matlab结构中的字段中的矩阵.
这是非常冗长的...让我解释一下:
我有一个matlab结构,定义如下:
matrixStruct = struct('matrix', {4, 4, 4; 5, 5, 5; 6, 6 ,6})
Run Code Online (Sandbox Code Playgroud)
我有一个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)));
}
Run Code Online (Sandbox Code Playgroud)
最终打印的内容如下:
4.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
Run Code Online (Sandbox Code Playgroud)
我也尝试了下面的变体,认为它可能是嵌套函数调用的东西,但无济于事:
/* 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 */
Run Code Online (Sandbox Code Playgroud)
有没有人知道如何实现我想要的,或者我可能做错了什么?
谢谢!
编辑:根据yuk的评论,我尝试在一个结构上做类似的操作,该结构有一个叫做数组的字段,它是一维的双精度数组.
包含数组的结构定义如下:
arrayStruct = struct('array', {4.44, 5.55, 6.66})
Run Code Online (Sandbox Code Playgroud)
我在mex函数中尝试了以下arrayStruct:
mptr = mxGetPr(mxGetField(prhs[0], 0, "array"));
printf("%f\n", *(mptr));
printf("%f\n", *(mptr + 1));
printf("%f\n", *(mptr + 2));
Run Code Online (Sandbox Code Playgroud)
...但是输出遵循之前打印的内容:
4.440000
0.000000
0.000000
Run Code Online (Sandbox Code Playgroud)
struct('field', {a b c})是构造函数的一种特殊形式,它创建一个与单元格数组大小相同的结构数组,将单元格的每个元素放入结构的相应元素的字段"字段"中.就是这样:
s = struct('field', {a b c});
Run Code Online (Sandbox Code Playgroud)
产生与此相同的结果:
s(1).field = a;
s(2).field = b;
s(3).field = c;
Run Code Online (Sandbox Code Playgroud)
您的问题的解决方案是使用方括号来形成常规(非单元格)数组,如下所示:
matrixStruct = struct('matrix', [4, 4, 4; 5, 5, 5; 6, 6 ,6]);
Run Code Online (Sandbox Code Playgroud)
您正在尝试访问 MATLAB 中的元胞数组变量。你确定数据是这样存储的吗?如果将双精度数组放入结构中会发生什么?
matrixStruct = struct('matrix', [4, 4, 4; 5, 5, 5; 6, 6 ,6])
Run Code Online (Sandbox Code Playgroud)
我认为问题在于 MATLAB 如何在元胞数组中存储数据。尝试运行这个:
double1 = 1;
double2 = 1:2;
cellempty = {[]};
celldouble1 = {1};
celldouble2 = {1:2};
cell2doubles = {1,2};
whos
Run Code Online (Sandbox Code Playgroud)
输出:
Name Size Bytes Class Attributes
cell2doubles 1x2 136 cell
celldouble1 1x1 68 cell
celldouble2 1x1 76 cell
cellempty 1x1 60 cell
double1 1x1 8 double
double2 1x2 16 double
Run Code Online (Sandbox Code Playgroud)
您可以看到元胞数组的每个元素额外占用了 60 个字节的数字大小。