Arrays from c to matlab.

8 views (last 30 days)
Roberto Neri
Roberto Neri on 10 Aug 2019
Commented: Roberto Neri on 11 Aug 2019
Hello everyone! This is my first time asking anything. I am trying to create a c file, call it "dostuff". This function dostuff(x,y) has 2 inputs and one output. one of those 2 inputs is the number of points which i need to work with. I have then to create a matrix with x columns and x rows in c and return this matrix (that i have already elaborated in c) back to matlab. I already wrote the code in c, and compiled with minGW from cmd and it works exactly as i wanted to. My problem is that i can't seem to find a way to return a vector or a matrix to matlab without it crashing. I'll send the code (in c) that i am trying to use to elaborate input and outputs:
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
// Create the pointer used in findmax function
double *p;
double *v;
double *connected_to;
// Define the output size (time_spent size)
v=mxGetPr(V);
/* Create a matrix for the return argument */
CONNECTIONS=mxCreateDoubleMatrix(1,(*v)*(*v), mxREAL);
/* Assign pointers to the various parameters */
// mxGetPr(mxArray) get the pointer of an mxArray element
p=mxGetPr(P);
connected_to=mxGetPr(CONNECTIONS);
/* Call the function previously defined */
dostuff(connected_to,v,p);
return;
My matlab code ha to enter v and p wich are the number of points and a probability, and i have to return the adjacency matrix of those given number of points. Matlab crashes everytime i try to run this mex function.
  8 Comments
Bruno Luong
Bruno Luong on 11 Aug 2019
Edited: Bruno Luong on 11 Aug 2019
And to be correct you should allocate with pointer size (which is incidently sameas sizeof(double) on 64-bit platform
matrix=(double**)malloc((*v)*sizeof(double*));
Roberto Neri
Roberto Neri on 11 Aug 2019
Thanks! i didn't noticed that bad error. But still it doesn't work.

Sign in to comment.

Answers (1)

James Tursa
James Tursa on 11 Aug 2019
v is pointer-to-double, *v is double. Everywhere inside generation() that you use v it needs to be *v instead.
  9 Comments
Bruno Luong
Bruno Luong on 11 Aug 2019
Replace it with mxGetPr
In your original code there is mxGetDouble (without "s"), this is unknown to me so I suppose there is a typo.
Roberto Neri
Roberto Neri on 11 Aug 2019
Bruno, Thank you so much, now it all seems to work exactly as i wanted to. Thank you for your time.

Sign in to comment.

Categories

Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!