我的 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<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/