Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: mex function for beginners
Replies: 13   Last Post: Aug 3, 2011 12:52 PM

 Messages: [ Previous | Next ]
 basudha pradhan Posts: 9 Registered: 8/23/07
mex function for beginners
Posted: Sep 1, 2007 2:26 AM

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.

Date Subject Author
9/1/07 Rune Allnor
9/1/07 Dan