Mex C++ create std::vector<double> from TypedArray<double>

31 次查看(过去 30 天)
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()

回答(1 个)

Amit P
Amit P 2019-5-9
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 个评论
Chen Dadon
Chen Dadon 2019-9-18
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
Daniele Nanni 2022-1-26
编辑:Daniele Nanni 2022-1-26
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!

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Write C++ Functions Callable from MATLAB (MEX Files) 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by