从 std::vector 在 MEX C++ 中创建 MATLAB 数组

Posted

技术标签:

【中文标题】从 std::vector 在 MEX C++ 中创建 MATLAB 数组【英文标题】:Create MATLAB Array in MEX C++ from a std::vector 【发布时间】:2020-09-20 01:58:32 【问题描述】:

我想知道是否有比我在下面所做和写的更优雅的方法来从 std::vector 创建 MATLAB 数组。

我在下面的 Matlab 论坛的一个问题中找到了一个更简单的实现,但问题仍然存在。 MathWorks: Copying std::vector contents to TypedArray

我使用缓冲区,基于matlab::data::SparseArrays 的制作方式 (C++ class to create arrays)。 免责声明:我对此真的很陌生!

假设我们有一个双精度向量 V

matlab::data::ArrayFactory f;

// these objects are std::unique_ptr<T[],matlab::data::buffer_deleter_t>
auto V_b_ptr = f.createBuffer<double>(V.size());

// this pointer points to the first adress that the std::unique_ptr points to
double* V_ptr = V_b_ptr.get();

// fill the buffer with the V values
std::for_each(V.begin(), V.end(), [&](const double& e) *(V_ptr++) = e; );

// finally create Matlab array from buffer
matlab::data::TypedArray<double> A = f.createArrayFromBuffer<double>(1, V.size(), std::move(V_b_ptr));

在第二个链接中,似乎有一种方法可以使用factory.createArray(...) 以填充给定数据的方式。但我无法让它工作。

【问题讨论】:

【参考方案1】:

经过数小时试图自己解决问题后,我写下了这个问题。但在提交之前,我又给了它一个小时。我终于设法做到了。我在这里发布解决方案,以防对任何人有帮助。

如问题中的示例所示,假设我们有一个 std::vector 的双精度数 V

matlab::data::ArrayFactory f;
matlab::data::TypedArray<double> A = f.createArray<double>(1, V.size(), V.data(), V.data()+V.size());

【讨论】:

以上是关于从 std::vector 在 MEX C++ 中创建 MATLAB 数组的主要内容,如果未能解决你的问题,请参考以下文章