matlab - c code translation

Hello, I'm trying to translate my code from Matlab to C in a mex file. But I encoutered some difficulties because Matlab has predefined functiones for almost everything.So this is my Matlab code:
% m=40;
% n=20;
% rap_V = abs(randn(m,n))
% for i = 4:m-3
% for j = 4:n-3
%
% im_A = rap_V(i-3:i+3,j-3:j+3);
% im_A = im_A(:);
And my C code from the mex file:
#include "math.h"
#include "mex.h" //--This one is required
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//Declarations
mxArray *xData;
double *xValues, *outArray;
int i,j,ii,jj,iii;
int rowLen, colLen;
//Copy input pointer x
xData = prhs[0];
//Get matrix x
xValues = mxGetPr(mxGetPr(xData));
rowLen = mxGetN(xData);
colLen = mxGetM(xData);
//Allocate memory and assign output pointer
plhs[0] = mxCreateDoubleMatrix(7*7, 1, mxREAL); //mxReal is our data-type
//Get a pointer to the data space in our newly allocated memory
outArray = mxGetPr(plhs[0]);
//Copy matrix while multiplying each point by 2
for(i=4;i<rowLen-3;i++)
{
for(j=4;j<colLen-3;j++)
{ int con=0;
for(ii=i-3; ii<=i+3; ii++)
for(jj=j-3; jj<=j+3; jj++)
{outArray[con] = xValues[(ii*7)+jj];
con=con+1;
}
}
}
My main problem is this line :
outArray[con] = xValues[(ii*7)+jj];
because it doesn't copy the right values of the input matrix into the 49*1 outArray. The aim is to copy the 7*7 matrixes into a 49*1 which I should use further on in my project. Any ideeas? }

1 Comment

Jan
Jan on 22 Nov 2011
Please apply a proper code formatting as explained in the "Markup help" link on this page. Currently your code is not readable.

Sign in to comment.

Answers (2)

Hi,
note that MATLAB sorts the values by column, i.e., you should use
xValues[rowLen*jj+ii]
instead.
Titus
Jan
Jan on 22 Nov 2011
This is one mexGetPr to much:
double *xValues;
mxArray *xData;
xData = prhs[0];
// xValues = mxGetPr(mxGetPr(xData)); % ERROR
xValues = mxGetPr(xData);

Categories

Asked:

on 22 Nov 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!