3

I want to pass an integer array from matlab to mex. The array is for example a=[1 2 3 4]. I wrote the following code:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <mkl.h>
#include "mkl_vml.h"
#include "mex.h"
#include "matrix.h"
#include "mkl_vsl.h"


/* main fucntion */
void mexFunction(int nlhs,  mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

    int n, *a;

    /* make pointers to input data */
    n = (int)mxGetScalar(prhs[0]);
    a = (int *)mxGetData(prhs[1]);

    mexPrintf("a[0]:%d \t a[1]:%d \t a[2]:%d \n", a[0],a[1],a[2]);

}

When I run it the result is:

a[0]:0   a[1]:1072693248     a[2]:0 

I've seen this answer : using integer arrays on mex but I haven't understood what to do.

Any help would be much appreciated.

Community
  • 1
  • 1
F.F.
  • 89
  • 7
  • As in the duplicate http://stackoverflow.com/questions/16783727/using-integer-arrays-on-mex, you need to pass `uint64(a)`, not just `a`. If that doesn't work or you don't understand, edit to give self-contained code for exactly how you call your mex file from matlab, i.e. you need to expand on "When I run". – Ramashalanka Oct 29 '15 at 23:18

1 Answers1

1

Here's a table is of equivalent C and MATLAB data types to use when deciding how to pass data.

enter image description here

Source.

Since you are dealing with an int * in the MEX file, you should be passing int32 MATLAB data. Note however that int in C is not guaranteed to be 32-bit, but seems to be so on modern systems.

chappjc
  • 30,359
  • 6
  • 75
  • 132