passing sparse arrays from matlab to Eigen (C++) and back to matlab?

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; }


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; }

    Reading and writing MATLAB/Octave sparse matrix adopted from here.

    </li> <li>

    Thanks to @chtz for their recommendations.

    </li> </ul>


  • From JPA to MyBatis: Composite Key?
  • How to use C# convert 2 dimensional array string[,] to string
  • Select query with dynamic column name, target table as well as dynamic where condition in i-batis
  • How do Rich Text Editors in HTML documents achieve their rich text formatting?
  • Trying to convert XML to JSON for JsTree (Javascript/Jquery)
  • VB.NET: Finding the size of text to be drawn, before it is drawn to a control
  • Z3py SMT coding following variables and the formulas
  • how to get a the value of an http post as a whole? parsing restful post
  • Needing Log Pcap
  • Facebook comments box not showing
  • Unable to publish web service which is created in java using eclipse
  • MATLAB, mex files, Fortran, warnings and errors
  • Lazy fetching in MyBatis
  • Strange sorting problem in PHP, mysql with utf8 data
  • Need advice to add exponenital back-off logic in AWS API in python
  • Java Formatter not allowing new line character?
  • Summing rows based on conditional in groups
  • ggplot2: Change color for each facet in bar chart
  • Adding Markers to Google Maps v3 After Map Created
  • Multiline edit in awk
  • How to work with 2D array returned from c function using Cython?
  • Importing from CSV from a specified range of values
  • MVVM in WPF - UserControls and GMap.NET
  • Opening Info Window when clicking a table row
  • Format HTML code with Python
  • Finding the start and stop indices in sequence in R
  • including a c/c++ header file in fortran subroutines
  • Make jQuery Wait For $.post to complete updating page
  • Smooks: Outputting EDI from Java
  • How to check if variable is Scalar or Array before mxIsScalar was introduced?
  • How to convert text file automatically to graphviz dot file?
  • FFTW advanced layout — inembed=n and inembed=NULL give different results?
  • Python Memory Ussage
  • Permit array in params
  • What is this error in fortran and how to stop the program when it occurs?
  • pandas computation in each group
  • How to add a column to a Pandas dataframe made of arrays of the n-preceding values of another column
  • script to move all files from one location to another location
  • Running Map reduces the dimensions of the matrices
  • Android Heatmap on canvas or ImageView