How to get a pointer to 2D array when writing a C source Mex file?
Mostrar comentarios más antiguos
Hi, I'm trying to write a highly simple C source .mex file (function) that takes a 1 x n vector and n x n matrix, and yields their matrix product, again a 1 x n vector (all the arrays are of binary and I'm doing computations for binary case). My concern is how to get a pointer to 2D array,(e.g the line arr = mxGetDoubles(prhs[1]);) I tried mxGetDoubles as it works for 1xn arrays, but I came across with the warning ": assignment from incompatible pointer type [-Wincompatible-pointer-types]". I then tried mxGetData; it did not give any warnings yet when I called the function from the command window, MATLAB crashed and was forced to close.
I would be highly appreciated if anyone can help me out. Thanks and here is the whole .c code:
/*==========================================================
* arrayMultiplier.c
*
* Multiplies a 1xN matrix with a N X N matrix
* and outputs a 1xN matrix
*
* The calling syntax is:
* outMatrix = arrayProduct(vector, array)
*========================================================*/
#include "mex.h"
/* The computational routine */
void arrayMultiplier( double *vec, double **arr, mwSize n ,double *z){
for (mwSize i=0; i<n; i++) {
for(mwSize j=0; j<n; j++) {
z[i] += vec[j]*arr[j][i];
}
z[i] = (double)((int)z[i] % 2);
}
}
/* The gateway function */
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {
double *vec;
double **arr;
mwSize nr;
double *outMatrix;
nr = mxGetN(prhs[0]); /*The "n" parameter of the 1 x n output matrix*/
vec = mxGetDoubles(prhs[0]);
arr = mxGetData(prhs[1]); /* This is where the warning appears */
/* creating the output matrix */
plhs[0] = mxCreateDoubleMatrix(1,nr,mxREAL);
/* get a pointer to the real data in the output matrix */
outMatrix = mxGetDoubles(plhs[0]);
/* call the computational routine */
arrayMultiplier(vec,arr,nr,outMatrix);
}
Respuesta aceptada
Más respuestas (1)
Walter Roberson
el 19 de Jul. de 2018
0 votos
mxGetDoubles will always be pointer to double, with the pointer being to the column-major linear storage of the data. To use this as a 2D array at the C level, you need to cast it to the appropriate double vec[m,n] declaration.
2 comentarios
Mustafa Aydin
el 20 de Jul. de 2018
KayLee Trickey
el 9 de Feb. de 2019
I am trying to do something similar to original poster, how do you cast it as the appropriate double declaration? I am knew to C and 2D arrays and pointers all all new to me.
In my c code, I use a lot of arr[i][j] indexing syntax.
Categorías
Más información sobre Resizing and Reshaping Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!