pillip wrote:
I am using data stored in a 20-20 array to find the mean of the rows and
columns, the results being stored in two other arrays. My problem is that
printf just gives the result for the first row and doesnt increment i. In
addition the integer j does not increment in printf either. (i, j being the
number of rows and columns respectively). Here is part of the code:
[corrected as per follow-up and re-indented for clarity]
for (j=0; j<column; j++) {
sumrows=0;
for (i=0; i<rows; i++) {
sumrows += ara[i][j];
}
for (i=0; i<rows; i++) {
sumcolumn=0;
sum=0;
for (j=0; j<column; j++) {
sum += ara[i][j]*j;
sumcolumn += ara[i][j];
}
meancolumn[column] = sum/sumcolumn;
meanrows[rows] = sumrows/rows;
printf("%d\t %13.10f\t %d\t %13.10f\n", i, meanrows[rows], j,
meancolumn[column]);
}
}
There are several things wrong here. Perhaps the most
conspicuous error is in the way the loops are nested: you
surely don't intend to have a loop on `j' inside another
loop on `j', do you? I'd say it was just a case of getting
the closing } brackets in the wrong places -- but then the
positioning of the mean calculations and of the printf()
call look sort of screwy, too ...
Rather than try to fix up what you've got -- it's so far
off the mark that "fix" isn't a verb that's easily applied --
I'll exhibit a substitute implementation.
/* Initialize totals to zero.
*/
for (j = 0; j < column; ++j)
meancolumn[j] = 0.0;
for (i = 0; i < rows; ++i)
meanrows[i] = 0.0;
/* Add each matrix element to its column total
* and to its row total. We're just accumulating
* raw totals at this point; we'll turn them into
* means later on.
*/
for (j = 0; j < column; ++j) {
for (i = 0; i < rows; ++i) {
meancolumn[j] += ara[i][j];
meanrows[i] += ara[i][j];
}
}
/* Scale totals by row or column count, and print
* them out.
*/
printf ("Column means:");
for (j = 0; j < column; ++j) {
meancolumn[j] /= rows;
printf (" %g", meancolumn[j]);
}
printf ("\n");
printf ("Row means:");
for (i = 0; i < rows; ++i) {
meanrows[i] /= column;
printf (" %g", meanrows[i]);
}
printf ("\n");
(The code could be written more compactly, but this version
may make for easier study.)
--
Er*********@sun.com