Pass data between C++ Eigen Matrix and MATLAB mxArray with a cell array

19 ビュー (過去 30 日間)
Bayes
Bayes 2019 年 3 月 9 日
コメント済み: Bayes 2019 年 3 月 9 日
I would like to pass data between Eigen Matrix/Vector and mex arrays. In the following code, I defined a mex array called y_output, which contains a cell array. The variable y_output will be passed to MATLAB. Each element in y_output is a vector but with different lengths. I would like to pass a pointer that points to Eigen vectors to the mex array y_output.
Notice that the data stored in y will be modified with a user-defined function. After calling the function, I would assume that the data stored in y_output will be modified corresponding. However, I cannot directly pass the pointer from y_output to y. Is there any way to make it possible? Thanks!
#include "mex.h"
#include "matrix.h"
#include <Eigen>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// prhs[0]: a cell array of length T, each element is a vector with different lengths
mwSize T = mxGetNumberOfElements(prhs[0]);
mwSize* n = new mwSize[T];
Eigen::VectorXd* z = new Eigen::VectorXd[T];
for(int t=0; t<T; t++){
n[t] = mxGetNumberOfElements(mxGetCell(prhs[0], t));
z[t] = Eigen::Map<Eigen::VectorXd>(mxGetPr(mxGetCell(prhs[0], t)), n[t]);
}
// create a cell matrix with T rows and one columns
mxArray* y_output = mxCreateCellMatrix(T,1);
// create corresponding Eigen objects
Eigen::VectorXd* y = new Eigen::VectorXd[T]();
Eigen::VectorXd y_temp(n[0]); y_temp.setZero();
for(int t=0; t<T; t++){
mxSetCell(y_output, t, mxCreateDoubleMatrix(n[t], 1, mxREAL));
y[t] = Eigen::VectorXd::Zero(n[t]);
y_temp.resize(n[t]);
Eigen::Map<Eigen::VectorXd> y[t](mxGetPr(mxGetCell(y_output, t)), n[t]); // This is not correct!
}
// Myfun(y, z); // y is modified
// set output
plhs[0] = y_output;
}
  1 件のコメント
Bayes
Bayes 2019 年 3 月 9 日
I figured a solution at Stack Overflow, see answer.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by