问题描述
我想知道用std::vector
创建MATLAB数组的方法是否比我在下面写的更优雅的方法。
我在下面的Matlab论坛中的一个问题中找到了一个更简单的实现,但是问题仍然存在。 MathWorks: Copying std::vector contents to TypedArray
我根据制造matlab::data::SparseArray
(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(...)
的方式来填充给定的数据。但是我无法使其正常工作。
解决方法
几个小时后,我试图自己弄清楚问题后才写了这个问题。但是在提交之前,我又给了一个小时。我终于做到了。我将解决方案发布在这里,以防它对任何人都有帮助。
就像问题中的示例一样,假设我们有一个std::vector
的双精度V
。
matlab::data::ArrayFactory f;
matlab::data::TypedArray<double> A = f.createArray<double>({1,V.size()},V.data(),V.data()+V.size());