Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert from float* to vector<float >

Tags:

c++

matlab

mex

I have a function float * pointwise_search(vector<float > &P,vector<float > &Q,float* n, int len ).

I want matlab call it so I need to write a mexFunction.

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{ 
    if (nrhs != 4)
    {
        mexErrMsgTxt("Input is wrong!");
    }

    float *n = (float*) mxGetData(prhs[2]);
    int len = (int) mxGetScalar(prhs[3]);
    vector<float > Numbers= (vector<float >)mxGetPr(prhs[0]);
    vector<float > Q= (vector<float >)mxGetPr(prhs[1]);

    plhs[1] = pointwise_search(Numbers,Q,n,len );

  }

But I found that vector<float > Numbers= (vector<float >)mxGetPr(prhs[0]); vector<float > Q= (vector<float >)mxGetPr(prhs[1]); are wrong.

So I have to change float * pointwise_search(vector<float > &P,vector<float > &Q,float* n, int len ) to float * pointwise_search(float *P,float *Q,float* n, int len ).

According to the answers, I rewrite as the following

 float * pointwise_search(float p,float *q,int num_thres, float n, int len ) 
{    vector<float> P{p, p + num_thres}; 
     vector<float> Q{q, q + num_thres}; 
     int size_of_threshold = P.size();
...
} 

But there occur errors.

pointwise_search.cpp(12) : error C2601: 'P' : local function definitions are illegal pointwise_search.cpp(11): this line contains a '{' which has not yet been matched

As the comment,I should change vector<float> P{p, p + num_thres}; to vector<float> P(p, p + num_thres);. :)

like image 710
Vivian Avatar asked Sep 14 '25 11:09

Vivian


1 Answers

Of course you can not generally convert a pointer to a vector, they are different things. If however the pointer holds the address of the first element of a C-style array of known length, you can create a vector with the same contents as the array like:

std::vector<float> my_vector {arr, arr + arr_length};

where arr is said pointer and arr_length is the length of the array. You can then pass the vector to the function expecting std::vector<float>&.

like image 107
Baum mit Augen Avatar answered Sep 16 '25 23:09

Baum mit Augen