Salida de una matriz con c ++ y mex

I have a problem with my c++ code. I want to return a matrix of k-dimensions from my cpp program to Matlab.

The matrix I want to pass is stored in all_data, and is a matrix of size (npoints+1) x ndims.

I have been looking how to do that, and I have come up with:

    //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 ];

But it does not work, as all_data es un vector<vector<double>> variable, and matlab says:

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

Can someone help me out? Thanks a lot!

preguntado el 24 de agosto de 12 a las 20:08

2 Respuestas

mxGetPr no devuelve un vector<vector<double> >. devuelve un double *. MATLAB arrays are stored contiguously in memory, column-major. Assuming you've created plhs[0] with the correct dimensions, then all you need to do is this:

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

Note the conversion of the 2 indices to a linear offset.

Respondido 24 ago 12, 20:08

are you sure about indexes[i + ndims1*j] ? i'd do i * (npoints1+1) + j. But i might be wrong. - ablm

In normal C, yes, you're right. But MATLAB, arrays are stored transposed of what we expect. So x(2,6) is right next to x(3,6). That's what "column-major" means. It's a leftover from FORTRAN days. - Peter

It looks like mxGetPr is returning you a pointer to an array of doubles and you are assigning it to a vector of vectors.

Esto debería funcionar:

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

Respondido 24 ago 12, 20:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.