3

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.

1 Answer 1

5

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());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.