【问题标题】:Output a matrix with c++ and mex用 c++ 和 mex 输出一个矩阵
【发布时间】:2012-08-25 18:27:35
【问题描述】:

我的 C++ 代码有问题。我想从我的 cpp 程序返回一个 k 维矩阵到 Matlab。

我要传递的矩阵存储在all_data,是一个大小为(npoints+1) x ndims的矩阵。

我一直在寻找如何做到这一点,我想出了:

    //send back points
    vector< vector <double> > indexes = mxGetPr(plhs[0]);
    for (int i=0; i < (npoints1+1); i++)
            for (int j=0; j < ndims1; j++)
                indexes[ i ][ j ] = all_data[ i ][ j ];

但它不起作用,因为all_data 是一个vector&lt;vector&lt;double&gt;&gt; 变量,而matlab 说:

error: conversion from 'double*' to non-scalar type 
'std::vector<std::vector<double, std::allocator<double> >, 
std::allocator<std::vector<double, 
std::allocator<double> > > >' requested

有人可以帮帮我吗?非常感谢!

【问题讨论】:

    标签: c++ matlab mex


    【解决方案1】:

    mxGetPr 不返回 vector&lt;vector&lt;double&gt; &gt;。它返回一个double *。 MATLAB 数组以列为主连续存储在内存中。假设您已经创建了具有正确尺寸的 plhs[0],那么您需要做的就是:

    double *indexes = mxGetPr(plhs[0]);
    for (int i=0; i < (npoints1+1); i++)
        for (int j=0; j < ndims1; j++)
            indexes[i + ndims1*j] = all_data[ i ][ j ];
    

    注意将 2 个索引转换为线性偏移量。

    【讨论】:

    • 你确定 index[i + ndims1*j] 吗?我会做 i * (npoints1+1) + j。但我可能错了。
    • 在普通的 C 语言中,是的,你是对的。但是在 MATLAB 中,数组是按照我们的预期存储的。所以 x(2,6) 就在 x(3,6) 旁边。这就是“专栏主要”的意思。这是 FORTRAN 时代的遗留物。
    【解决方案2】:

    看起来 mxGetPr 正在向您返回一个指向双精度数组的指针,并且您正在将它分配给一个向量向量。

    这应该可行:

    double* indexes = mxGetPr(plhs[0]);
    

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      相关资源
      最近更新 更多