Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create MATLAB Array in MEX C++ from a std::vector

I would like to know if there is a more elegant way to create a MATLAB array from a std::vector than what I did and wrote below.

I found a simpler implementation in a question in the following Matlab forum, but the question still persists. MathWorks: Copying std::vector contents to TypedArray

I used buffers, based on the way matlab::data::SparseArrays are made (C++ class to create arrays). Disclaimer: I'm really new to this!

Suppose we have a vector V of doubles:

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));

In the second link, there seems to be a way to use factory.createArray(...) in such a way that it is filled with a given data. But I wasn't able to make it work.

like image 929
Breno Avatar asked Mar 31 '26 02:03

Breno


1 Answers

I wrote the question after hours of trying to figure things out by myself. But before submitting it, I gave it another hour. And I finally managed to do it. I'm posting the solution here in case it helps anyone.

As in the example in the question, supposing we have 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());
like image 71
Breno Avatar answered Apr 02 '26 02:04

Breno