将稀疏数组从matlab传递到Eigen(C ++),然后再返回到matlab? [英] passing sparse arrays from matlab to Eigen (C++) and back to matlab?
本文介绍了将稀疏数组从matlab传递到Eigen(C ++),然后再返回到matlab?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是使用Eigen将matlab中的密集数组g和G相乘的mex代码. g稀疏时该怎么办?
The following is a mex code that multiplies dense arrays g and G from matlab using Eigen. How do I do this when g is sparse?
#include <iostream>
#include <Eigen/Dense>
#include "mex.h"
using Eigen::MatrixXd;
using namespace Eigen;
/*gateway function*/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
int nRows=(int)mxGetM(prhs[0]);
int nCols=nRows;
double* g=mxGetPr(prhs[0]);
double* Gr=mxGetPr(prhs[1]);
Map<MatrixXd> gmap (g, nRows, nCols );
Map<MatrixXd> Grmap (Gr, nRows, nCols );
plhs[0] = mxCreateDoubleMatrix(nRows, nCols, mxREAL);
Map<MatrixXd> resultmap (mxGetPr(plhs[0]), nRows, nCols);
resultmap = gmap*Grmap;
}
推荐答案
您可以使用这些函数在MATLAB和Eigen *之间传递稀疏(压缩)双精度矩阵:
You can use these functions to pass sparse (compressed) double matrix between MATLAB and Eigen* :
#include "mex.h"
#include <Eigen/Sparse>
#include <type_traits>
#include <limits>
using namespace Eigen;
typedef SparseMatrix<double,ColMajor,std::make_signed<mwIndex>::type> MatlabSparse;
Map<MatlabSparse >
matlab_to_eigen_sparse(const mxArray * mat)
{
mxAssert(mxGetClassID(mat) == mxDOUBLE_CLASS,
"Type of the input matrix isn't double");
mwSize m = mxGetM (mat);
mwSize n = mxGetN (mat);
mwSize nz = mxGetNzmax (mat);
/*Theoretically fails in very very large matrices*/
mxAssert(nz <= std::numeric_limits< std::make_signed<mwIndex>::type>::max(),
"Unsupported Data size."
);
double * pr = mxGetPr (mat);
MatlabSparse::StorageIndex* ir = reinterpret_cast<MatlabSparse::StorageIndex*>(mxGetIr (mat));
MatlabSparse::StorageIndex* jc = reinterpret_cast<MatlabSparse::StorageIndex*>(mxGetJc (mat));
Map<MatlabSparse> result (m, n, nz, jc, ir, pr);
return result;
}
mxArray*
eigen_to_matlab_sparse(const Ref<const MatlabSparse,StandardCompressedFormat>& mat)
{
mxArray * result = mxCreateSparse (mat.rows(), mat.cols(), mat.nonZeros(), mxREAL);
const MatlabSparse::StorageIndex* ir = mat.innerIndexPtr();
const MatlabSparse::StorageIndex* jc = mat.outerIndexPtr();
const double* pr = mat.valuePtr();
mwIndex * ir2 = mxGetIr (result);
mwIndex * jc2 = mxGetJc (result);
double * pr2 = mxGetPr (result);
for (mwIndex i = 0; i < mat.nonZeros(); i++) {
pr2[i] = pr[i];
ir2[i] = ir[i];
}
for (mwIndex i = 0; i < mat.cols() + 1; i++) {
jc2[i] = jc[i];
}
return result;
}
-
读取和编写从这里.
感谢@chtz的推荐.
Thanks to @chtz for their recommendations.
这篇关于将稀疏数组从matlab传递到Eigen(C ++),然后再返回到matlab?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文