# MATLAB: How to obtain the memory address for a variable in MATLAB 7.7 (R2008b)

I am using variables of different types such as doubles, structs and objects in my MATLAB code. I would like to obtain the memory location at which they are stored by MATLAB.

The address of a MATLAB variable can be obtained using a MEX function.
The gateway routine of a MEX function has the following signature:
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]);
Here prhs is an array of right-hand input arguments. It is an array of pointers to type mxArray. When a variable is passed as an input argument to a MEX function, the pointer to that variable is copied into prhs.
For example, if a MEX function, 'myMexFunction', is called using one input argument as shown below:
a = 5;myMexFunction(a);
the address of the variable 'a' is copied into prhs[0].
The following C-MEX function, "mem_address.c", illustrates how you can obtain the address of each element of a row vector of type double. This code can be expanded to operate on other data-types as well.
#include "mex.h"void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){    double *ptr;    int i;    mwSize n;      /* Function accepts only one input argument */      if(nrhs > 1)      {          mexErrMsgTxt("Only one input argument accepted\n\n");      }         /* This function works only with row vectors */      if( mxGetM(prhs[0]) > 1 )      {          mexErrMsgTxt("Only row vectors are accepted\n\n");      }      /* Get the Pointer to the Real Part of the mxArray */      ptr = mxGetPr(prhs[0]);      n = mxGetN(prhs[0]);      mexPrintf("Pointer Address of mxArray = %x\n\n", prhs[0]);      for(i = 0; i < n; i++)      {          mexPrintf("Value of Real Argument at array index %d = %f\n", i, ptr[i]);          mexPrintf("Pointer Address = %x\n\n", &ptr[i]);      }  }
You can MEX this C-file using the following command at the MATLAB prompt:
mex mem_address.c
This will generate a MEX file with an extension depending on your platform. You can run this MEX file as follows:
a = 5;mem_address(a);