在Matlab的mex函数中使用预分配的数组 [英] Working with preallocated arrays in Matlab's mex function
问题描述
我编写了一个简单的mex函数,该函数会更新Matlab数组已分配的内容:
I wrote a simple mex function which updates already allocated by Matlab array:
mex_test_array.c
mex_test_array.c
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *x = mxGetPr(prhs[0]);
x[0] = 3.1416;
}
测试1:
>> y = zeros(2, 2);
>> mex_test_array(y);
>> y
y =
3.1416 0
0 0
测试2:
>> y = zeros(2, 2);
>> mex_test_array(y(:, 1));
>> y
y =
0 0
0 0
为什么在子矩阵上不起作用(测试2)?有可能使其工作吗?
Why it doesn't work on sub-matrix (Test 2) ? Is it possible to make it work?
请告知.
备注: 我了解,更新输入数组并不是应如何编写mex文件,而且我确实知道如何从mex返回数组. 我尝试此技术的原因是避免两次分配数组的内存.
Remark: I understand, that updating input arrays is not how mex files are expected to be writted, and I do know how to return arrays from mex. The reason I tried this technique is to avoid allocation of the arrays' memory twice.
推荐答案
由于 MATLAB不想更改右侧参数",因此不应该起作用强>.参见例如在线帮助:
prhs [是]输入数据的指针数组.输入数据是只读的, 不应通过您的mexFunction进行更改.
prhs [is an] Array of pointers to input data. The input data is read-only and should not be altered by your mexFunction .
这就是为什么您的函数标头
That is why your function header
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
表示const mxArray *prhs[]
,而不是mxArray *prhs[]
.如果要返回一个值,则应该 通过mxArray *plhs[]
进行操作.我认为更改右侧参数"时的行为只是不确定的,建议阅读完整的
says const mxArray *prhs[]
and not mxArray *prhs[]
. If you want to return a value, you are supposed to do that through mxArray *plhs[]
. I think the behaviour for when you change a "right-hand-side parameter" is just undefined and recommend reading the full MEX files guide for further details.
更新
要回答您的实际问题,我假设当您将y
交给函数时,MATLAB会为您提供实际的指针,并且(错误地)相信您不会弄乱它;当您移交函数y(:,1)
时,MATLAB会复制数组的该部分,并为您提供指向该副本的指针,该指针在函数调用后将被丢弃.
To answer your actual question, I assume that when you hand y
to your function, MATLAB hands you the actual pointer and (falsely) trusts you not to mess with it; when you hand your function y(:,1)
MATLAB makes a copy of that part of the array and hands you a pointer to that copy, which is discarded after your function call.
如果您坚持这样做,请至少阅读 reve_etrange 的注释中指出,nofollow noreferrer>在未公开记录的Matlab上进行Matlab mex就地编辑一个>!本质上,您必须运行
If you do insist on doing this, at least read Matlab mex in-place editing on Undocumented Matlab, as pointed out in the comments by reve_etrange! Essentially, you must run
mxUnshareArray(const_cast<mxarray *>(prhs[0]), true);
在修改该数组之前.否则运行
before you modify that array. Otherwise running
>> y = zeros(2, 2);
>> y_backup=y;
>> mex_test_array(y);
将导致
>> y
y =
3.1416 0
0 0
>> y_backup
y =
3.1416 0
0 0
...这导致了一些无法维护的代码!
... which makes for some hell-of-a-unmaintainable code!
这篇关于在Matlab的mex函数中使用预分配的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!