I have a stupid problem which apparently I cannot solve alone. I want
export some computations I do in Matlab to C.
The C code below shall write the data of a Matlab matrix into a
vector. Therefore I use two nested for-loops.
//---------------------------------------------------------------------------------------------------------------------
// beispiel.cpp
//---------------------------------------------------------------------------------------------------------------------
#include <mex.h>
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray
*prhs[] ) {
int n = mxGetN(prhs[0]);
int m = mxGetM(prhs[0]);
int u = 0;
double* punc_pat_mat = mxGetPr(prhs[0]);
plhs[0] = mxCreateDoubleMatrix(1, n*m , mxREAL);
double* punc_pat_row = mxGetPr(plhs[0]);
mexPrintf("%d Spalten\n", n);
mexPrintf("%d Zeilen\n", m);
for (int ii = 0 ; ii<(n-1) ; ii++ )
{ // line 14
for (int i = 0 ; i<(m-1) ; i
+ ) // line 15
{
punc_pat_row[u] = punc_pat_mat[ii+i*n];
u++;
}
}
}
---------------------------------------------------------------------------------------
It is supposed to work but there is a syntax error concerning the two
for loops. Here is the compiler output:
beispiel.cpp(15) : error C2059: syntax error : ')'
beispiel.cpp(16) : error C2143: syntax error : missing ';' before '{'
I tried a lot but every change doesn't make it better and looks
stupid! What do I wrong? I would be very grateful for your help.
Thanks in advance.
regards, Bernhard
and here is my mistake! it must be i++ instead of i+ *noob*. I guess I
am tired out!
You've answered your own question but there is something else that's a
little odd here (to a C programmer).
The form index ii + i * n is the normal way to access a 1D array as if
it were a 2D one. Nothing odd there: n is the 'span' (the width or
height of a row or column depending on usage). But if that is what is
happening here, the loop bounds look very peculiar. As far as the body
of the loop is concerned, ii will run from 0 up to and including n-2 and
i will run from 0 up to and including m-2. As soon as ii is incremented
to n-1 the loop condition fails and the loop body is not executed. The
same applies when i becomes m-1
For example, if m and n are both 3, punc_pat_mat is access with i=0 and
i=1 and with ii=0 and ii=1. You will access elements
0 + 0 * 3 == 0
0 + 1 * 3 == 3
1 + 0 * 3 == 1
1 + 1 * 3 == 4
(or 0, 1, 3, 4 when sorted). I'd expect 0, 1, 2, 3, 4, 5, 6, 7, 8 or
maybe 0, 1, 2, 3.
Also (minor point) it may be worth swapping the loops so that the
accesses are consecutive rather than "interleaved" (if you see what I
mean).
> u++;
> }
> }
> }
<snip>
--
Ben.