c++ - 从 std::vector 在 MEX C++ 中创建 MATLAB 数组
问题描述
我想知道是否有std::vector
比我在下面所做和编写的更优雅的方法来从 a 创建 MATLAB 数组。
我在以下 Matlab 论坛的一个问题中找到了一个更简单的实现,但问题仍然存在。MathWorks:将 std::vector 内容复制到 TypedArray
我使用缓冲区,基于matlab::data::SparseArray
s 的制作方式(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(...)
给定数据填充的方式。但我无法让它工作。
解决方案
经过数小时试图自己解决问题后,我写了这个问题。但在提交之前,我又给了它一个小时。我终于设法做到了。我在这里发布解决方案,以防它帮助任何人。
如问题中的示例所示,假设我们有 a std::vector
of doubles V
。
matlab::data::ArrayFactory f;
matlab::data::TypedArray<double> A = f.createArray<double>({1, V.size()}, V.data(), V.data()+V.size());
推荐阅读
- delphi - RAD Studio 10.2.3 Jedi JVCL 安装问题
- c++ - 什么可以用作 C/C++ 中#define 指令的标识符
- filehelpers - 如何正确调用 FileHelpers.RecordTypeSelector?
- javascript - IntersectionObserver 和 ajax 加载的内容
- css - 在 React 构建中,背景不会从外部 CSS 加载
- php - WordPress - 将用户设置为在某个日期后过期
- reactjs - 在非弹出的 create-react-app 中覆盖 eslint 设置?
- filepond - Filepond、DELETE 请求和文件名
- angular - Angular 7 取消的 HTTP 请求未反映在核心 API 中
- powershell - 使用特定 NIC 测试连接性