首页 > 解决方案 > 从 std::vector 在 MEX C++ 中创建 MATLAB 数组

问题描述

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

我在以下 Matlab 论坛的一个问题中找到了一个更简单的实现,但问题仍然存在。MathWorks:将 std::vector 内容复制到 TypedArray

我使用缓冲区,基于matlab::data::SparseArrays 的制作方式(C++ 类创建数组)。免责声明:我对此真的很陌生!

假设我们有一个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(...)给定数据填充的方式。但我无法让它工作。

标签: c++arraysmatlabvectormex

解决方案


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

如问题中的示例所示,假设我们有 a std::vectorof doubles V

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

推荐阅读