c++ - 用c++和mex输出一个矩阵

标签 c++ matlab mex

我的 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_datavector<vector<double>>变量,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

有人能帮帮我吗?非常感谢!

最佳答案

mxGetPr不返回 vector<vector<double> > .它返回 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 个索引转换为线性偏移量。

关于c++ - 用c++和mex输出一个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12115584/

相关文章:

C++:ToUnicode 函数上的 SIGSEGV (windows)

matlab - matlab中的L1范数等高线图

matlab - MatLab环境中的if语句

c - 释放 C 库中的静态结构

c++ - 强制 gstreamer appsink 缓冲区只保存 10ms 的数据

c++ - 将通用 Lambda 与 std::find_if 结合使用

c++ - 如何使用 GTest 测试严重依赖 MFC 的方法

arrays - 3d 矩阵中 `repmat` 和 `permute` 的更快替代方案?

c++ - 如何让 MatLab 找到 Visual C++ 编译器?

c++ - Visual Studio Code 无法启动 MATLAB