本文介绍了复制多维C数组到Matlab mxArray类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个打开Matlab API引擎的c ++代码。在演示文件Matlab_ROOT / extern / examples / eng_mat / engdemo.cpp中,它显示了如何将一个简单的1d c样式数组复制到mxArray:

I'm writing a c++ code that opens Matlab API engine. In the demo file Matlab_ROOT/extern/examples/eng_mat/engdemo.cpp, it shows how to copy a simple 1d c style array to a mxArray:

mxArray *T = NULL; double time[10] = {};
T = mxCreateDoubleMatrix( 1,10,mxREAL);
memcpy((void*)mxGetPr(T), (void*)time, sizeof(time));

我可以理解这段代码;因此1d mxArray 对象用线性存储元素。

I can understand this code; so a 1d mxArray object stores the elements linearly.

但是,假设我有一个2d(或更多)的c数组,并且 mxArray >

However, suppose I have a 2d (or more) c array and mxArray of same size:

double time[3][5]; 
mxArray *T; 
T = mxCreateDoubleMatrix(3,5,mxREAL);

,我想将c数组时间的元素复制到 mxArray T 。我如何做到这一点?我想如果我使用 memcpy ,它将取决于元素存储在 mxArray 对象的顺序。非常感谢!

and I want to copy the elements of the c array time into mxArray T. How can I do this? I suppose if I use memcpy, it would depend on the sequence of element storage in mxArray objects. Thanks!

推荐答案

无论你的 mxArray 将其作为连续块存储在存储器中(列第一顺序)。也就是说,如果你的矩阵 M 是2乘3

No matter what the dimensionality of your mxArray matlab always stores it as a continuous chunk in memory (column first order). That is, if your matrix M is 2-by-3

M = [ 11, 12, 13;
      21, 22, 23 ];

在内存中,Matlab将其存储为

In memory, Matlab stores it as

[11, 21, 12, 22, 13, 23]

(如果您 M(:)),您会得到相同的顺序。

(The same order you'll get if you do M(:)).

double [3] [5] 转换为 mxArray ,您必须发出 > memcpy 命令:

Therefore, to convert a double[3][5] to mxArray you'll have to issue several memcpy commands:

double* ptr = mxGetPr( T );
for ( int i=0; i<3; i++ )
    memcpy( (void*)(ptr+i*5), (void*)time[i], 5*sizeof(double) );

这篇关于复制多维C数组到Matlab mxArray类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 21:11