为什么我的混合特征码会打印出错误的矩阵条目?

Why does my mexed eigen code print out the wrong entries of the matrix?

以下是从 Matlab 中获取稀疏矩阵的 C++ 代码。

#include "mex.h"
#include <Eigen/Sparse>
#include<iostream>
using namespace Eigen;
using namespace std;


void mexFunction( int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[]) {

    mwSize     m = mxGetM (prhs[0]);
    mwSize     n = mxGetN (prhs[0]);
    mwSize    nz = mxGetNzmax (prhs[0]);
    double  * pr = mxGetPr (prhs[0]);
    int * ir = (int*) mxGetIr (prhs[0]);
    int * jc = (int*) mxGetJc (prhs[0]);
    Map<SparseMatrix<double> > gmap (m, n, nz, jc, ir, pr);

    cout << gmap.coeffRef(0,0);
    cout << gmap.coeffRef(0,1)<< "\n";

    cout << gmap.coeffRef(1,0);
    cout << gmap.coeffRef(1,1)<< "\n";

}

我只是将一个小型稀疏格式的 2x2 矩阵传递给它并打印出条目。为什么输入错误?这是 Matlab 命令 window:

的输出
>> a=magic(2)

a =

     1     3
     4     2

>> example(sparse(a))
11
13

更新:感谢评论中的建议,已解决。我会 post 回答。

我已经根据评论中的建议更新了代码,现在可以使用了。

  1. 我已将 int* 更改为 mwIndex*。

  2. 我复制了 mwIndex* 数组 ir 和 jc 数组,将每个条目重新转换为 int,以便它与 Eigen 兼容。这样编译成功。这是修改后的工作代码:

    #include "mex.h"
    #include <Eigen/Sparse>
    #include<iostream>
    using namespace Eigen;
    using namespace std;
    
    
    void mexFunction( int nlhs, mxArray *plhs[],
            int nrhs, const mxArray *prhs[]) {
    
        mwSize     m = mxGetM (prhs[0]);
        mwSize     n = mxGetN (prhs[0]);
        mwSize    nz = mxGetNzmax (prhs[0]);
        double  * pr = mxGetPr (prhs[0]);
        mwIndex * ir = mxGetIr (prhs[0]);
        mwIndex * jc = mxGetJc (prhs[0]);
    
        //copy and cast mwIndex
        int* ir_int=(int*)mxMalloc(nz*sizeof(int));
        int* jc_int=(int*)mxMalloc(nz*sizeof(int));
        for (int ii=0;ii<nz;ii++){
           ir_int[ii]=(int) ir[ii];   
           jc_int[ii]=(int) jc[ii]; 
        }
    
        Map<SparseMatrix<double> > gmap (m, n, nz, jc_int, ir_int, pr);
    
        cout << gmap.coeffRef(0,0);
        cout << gmap.coeffRef(0,1)<< "\n";
    
        cout << gmap.coeffRef(1,0);
        cout << gmap.coeffRef(1,1)<< "\n";
    
    }
    

    magic(2)

    答案=

     1     3
     4     2
    

    example(sparse(magic(2))) 13 42