how to pass 2D array from c++ to matlab via mex new c++ api

조회 수: 18 (최근 30일)
Chen Dadon
Chen Dadon 2019년 9월 18일
답변: Zehui Lu 2020년 3월 31일
Hi, i am trying to understand how to cast matlab variables and c++ variables
lets say i want to pass matrix i created in c++ (2D or 1D float array) to matlab.
i am using the new C++ api
i have tried something like:
CMatrixType2D<float> m_mfImage; //create matrix
m_mfImage.Init(m_Alg.mConfig.uiHeight, m_Alg.mConfig.uiWidth);//init matrix
aOutput.m_pmuiImage = &m_mfImage;
//Execute Algorithm
m_Alg.Execute(&aInput, &aOutput);//create frame output
outputs[0] = factory.createArray<float>({ m_Alg.mConfig.uiHeight , m_Alg.mConfig.uiWidth }, aOutput.m_pmuiImage);
but i cant figure how to convers/cast TypedArray to cpp array or get a pointer to work with.

답변 (1개)

Zehui Lu
Zehui Lu 2020년 3월 31일
I'm using Savyasachi Singh's template here to get the pointer of a TypedArray. Then I map this pointer to an Eigen matrix for the heavy computation. The example is like the following. Note that to use external c++ libraries with C++ MEX API, we need to write a wrapper (e.g. compute_something_with_eigen.cpp), and operator() can internally use this function. After we finish the computation with external libraries, we can find the pointer of this result matrix and map it back to a TypedArray.
// Assign the input, assume it's a 2D matrix
TypedArray<double> matrix = std::move(inputs[0]);
// Use the template I mentioned above
double* ptr = getPointer(matrix);
// Get the dimension of input
size_t size_input = matrix.getDimensions();
// Don't do the following in your C++ MEX main file
MatrixXd mat_eig = Map<MatrixXd>(ptr,size_input[0],size_input[1]);
// Do your algorithm

카테고리

Help CenterFile Exchange에서 Write C++ Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by