Mex C++ create std::vector<double> from TypedArray<double>
10 views (last 30 days)
Show older comments
I'm using mex and C++, and I'm trying to convert a Matlab TypedArray<double> into a c++ std::vector<double>
ObjectArray obj(inputs[0]);
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
matlab::data::TypedArray<double> foo = matlabPtr->getProperty(obj, u"foo")
I'm trying to avoid the below, just looping through and adding each value because that seems very inefficient on large vectors.
std::vector<double> bar;
for (auto& elem : inArray) {
bar.push_back(inArray);
}
I was hoping there was some way of just accessing the underlying vector directly.
std::vector<double> bar = foo.someFunc()
0 Comments
Answers (1)
Amit P
on 9 May 2019
You can use the iterator available in the TypedAray.
ObjectArray obj(inputs[0]);
std::shared_ptr<matlab::engine::MATLABEngine> matlabPtr = getEngine();
matlab::data::TypedArray<double> foo = matlabPtr->getProperty(obj, u"foo")
//Use the iterator here
std::vector<long double> dest(foo.begin(), foo.end());
Hopefully this helps.
2 Comments
Chen Dadon
on 18 Sep 2019
Hi, do you know if i can cast TypedArray to cpp variable?
lets say i create matrix and my function to modify this matrix can get only ptr to float how can i cast the ptr?
TypedArray<float> Mat = factory.createArray<float>({ Height , uiWidth });
float *pWrapedMat = (float*)Mat; //crash
m_mfImage.Init(Height, uiWidth, pWrapedMat);//wraping the matrix
aOutput.m_pmuiImage = &m_mfImage;
//Execute Algorithm
m_Alg.Execute(&aInput, &aOutput);//create frame output
outputs[0] = std::move(aOutput);
Daniele Nanni
on 26 Jan 2022
Edited: Daniele Nanni
on 26 Jan 2022
Hi,
It work smooth for a single vector, but what if the obj is a matrix?
I have tried your solution and when I apply:
ObjectArray obj(inputs[0]); // Obj_INET_ONET
TypedArray<std::complex<float>> inet_matrix = matlabPtr->getProperty(obj, u"inet_matrix");
matlab::data::ArrayDimensions size_matrix = inet_matrix.getDimensions();
std::vector<std::complex<float>> inet_vec(inet_matrix.begin(), inet_matrix.end());
the inet_vec contains the matrix inet_matrix (40x8) as a long vector (so as 1x40*8). I need to have a matrix in c++ for do some operations in the script and then send back to matlab the result. How can I do that?
Thanks since now for your time to answer me!
See Also
Categories
Find more on Write C++ Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!