Hey there, I don't really understand how to access data passed via arguments in matlab to a mex-function. Assuming I have the 'default' gateway function
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
And now I get the pointer to the 1. input argument:
double* data_in;
data_in = mxGetPr(prhs[0]);
Both the following lines EACH seperatly make my matlab crash:
mexPrintf("%d", *data_in);
mexPrintf("%d", data_in[1]);
But why can't I access the data like that when data_in obvisously is a pointer to the first argument?
- When do I need to declare the pointer as double* and when as mxArray*? Some开发者_开发知识库times I see something like that: mxArray *arr = mxCreateDoubleMatrix(n,m,mxREAL);!?
Thanks a lot in advance!
data_in
is a pointer to double
so you need something like
mexPrintf("%f", data_in[0]);
This assumes the caller passed a vector or matrix of size > 0.
More generally, you can
int n = mxGetN(array);
int m = mxGetM(array);
To get the number of rows and columns of the matrix/vector passed to the mex function.
Regarding mxArray
:
Matlab packs its matrices (complex and real) in an mxArray structure. mxCreateDoubleMatrix
returns a pointer to such structure. To actually access that data you need to use mxGetPr() for the real part and mxGetPi() for the imaginary parts.
These return pointers to the allocated double[]
arrays, which you can use to access (read and write) the elements of the matrix.
A very convenient way of handling dimensions of mxArrays is to introduce a function like the following.
#include <cstddef>
#include <cstdarg>
#include "mex.h"
bool mxCheckDimensions(const mxArray* mx_array, size_t n_dim,...) {
va_list ap; /* varargs list traverser */
size_t *dims; /* dimension list */
size_t i;
size_t dim;
bool retval = true;
va_start(ap,n_dim);
dims = (size_t *) malloc(n_dim*sizeof(size_t));
for(i=0;i<n_dim;i++) {
dims[i] = va_arg(ap,size_t);
dim = mxGetDimensions(mx_array)[i];
if (dim != dims[i])
retval = false;
}
va_end(ap);
free(dims);
return retval;
}
In this way you check an array mxArray* p is a double array of size say 1,3 using
double* pDouble = NULL;
if (mxIsDouble(p)) {
if (mxCheckDimensions(p, 2, 1, 3)) {
pDouble = (double*) GetData(p);
// Do whatever
}
}`
精彩评论