2017-04-02 31 views
0

如何將Eigen Matrix作爲Matlab輸出參數傳遞?將C++特徵矩陣傳遞給Matlab mex輸出

我想這從[EIGEN] How to get in and out data from Eigen matrix:

MatrixXd resultEigen; // Eigen matrix with some result (non NULL!) 
double *resultC;    // NULL pointer 
Map<MatrixXd>(resultC, resultEigen.rows(), resultEigen.cols()) = resultEigen; 

但它缺乏信息,如何通過在resultC到plhs [0]的信息?另外,當我使用這個Map運行代碼時,Matlab關閉。

+0

你不能''Eigen矩陣'''Matlab'。你可以做的是使用'Eigen'計算大量數據,並使用底層數據創建一個對象,該對象可以被'Matlab'理解並添加到'plhs'中。 –

回答

2

您需要首先分配輸出MATLAB陣列,然後創建一個Eigen::Map周圍:

MatrixXd resultEigen; // Eigen matrix with some result (non NULL!) 
mwSize rows = resultEigen.rows(); 
mwSize cols = resultEigen.cols(); 
plhs[0] = mxCreateDoubleMatrix(rows, cols, mxREAL); // Create MATLAB array of same size 
Eigen::Map<Eigen::MatrixXd> map(mxGetPr(plhs[0], rows, cols); // Map the array 
map = resultEigen; // Copy 

這樣做是使具有MATLAB陣列的特徵矩陣(map)(plhs [0])作爲數據。當你寫入它時,實際上是在寫入MATLAB數組。

請注意,您可以在進行Eigen計算之前創建此地圖,並使用它代替resultEigen,以避免最終副本。

還要注意,你可以對輸入數組做同樣的事情。只要確保他們的類double(使用mxIsDouble),或者事情可能會發生可怕的錯誤... :)

[免責聲明:我沒有編譯此代碼,但我寫了類似的代碼。請讓我知道,如果我錯誤鍵入了一些東西!]