Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.
|
|
Dan
Posts:
18
Registered:
8/2/07
|
|
Re: mex function for beginners
Posted:
Sep 1, 2007 10:32 AM
|
|
"basudha pradhan" <lucky_faith_911@hotmail.com> wrote in message <fbb0lu$7b3$1@fred.mathworks.com>... > I just started learning writing mex function. In C function > bitplan(), it take integer array as an input and it convert > each element of array from decimal to 8 bit binary. then > MSB of every element is taken and written to a file, after > that next significant bit of every element is taken and > written to a file. In this way integer array is separated > into bit plane. > > I have tested the C function it works properly. But mex > function that i wrote doesn't give the correct output. > However it compiles with no error. > > Here is what i tried. > > #include <stdlib.h> > #include <string.h> > #include <stdio.h> > #include <math.h> > #include "mex.h" > > bitplan(int x[]) > { > int i,j,k; > FILE *fp; > struct tag{ > int label; > char bin[9]; > }; > struct tag data[100]; > char bvalue[9]; > int index; > int temp_value, decimal_value; > fp = fopen("qdata.txt","w"); > for(i=0;i<100;i++) > { > data[i].label=i; > decimal_value=x[i]; > for(index=8;index>=0;index--) > { > // temp_value=decimal_value/pow(2,index) > temp_value=decimal_value/(1<<index); > if(temp_value>0) > { > bvalue[index]=(char)('0'+temp_value); > // decimal_value=decimal_value%pow(2,index) > decimal_value=decimal_value%(1<<index); > } > else > { > bvalue[index]='0'; > } > data[i].bin[index]=bvalue[index]; > } > > for(j=0;j<8;j++) > { > for(k=0;k<100;k++) > { > fprintf(fp,"%c",data[k].bin[j]); > } > } > fclose(fp); > > } > } > > void mexFunction(int nlhs, mxArray *plhs[], > int nrhs, const mxArray *prhs[]) > { > /* Declare variables. */ > int elements, number_of_dims; > int *pr, *pind; > > > /* Check for proper number of input and output arguments. > */ > if (nrhs != 1) { > mexErrMsgTxt("One input argument required."); > } > > > /* Get the number of elements in the input argument. */ > elements = mxGetNumberOfElements(prhs[0]); > > /* Get the data. */ > pr = (int *)mxGetPr(prhs[0]); > bitplan(pr); > } > > > Any suggestion would be greatly appreciated. > > Thanks, > Basudha.
How are you passing your variables into the mex function? If I use your code and pass in a double matrix I get bad data in pr. However if I cast the data as an int32 in Matlab prior to passing the variable into the mex function I get the proper data in pr.
It is probably best to use mxGetData instead of mxGetPr so you get a void* back instead of a double*.
Dan
|
|
|
|