# Mean of the columns in a matrix

This topic is 3377 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I need to take mean of each column of a matrix(MxN) I have the code given below. But I am getting some junk values as mean. Whats wrong with my logic.

#include <stdio.h>

#define N 3
#define M 2

void Compute_Mean(float* observations, float* mean)
{
float sum;

for(int i=0;i<M;i++)
{
sum = 0.0f;
for(int j=0;j<N;j++)
{
//accessing the column.
printf("%f\n",observations[j*N+i]);
sum += observations[j*M+i];
}
mean[i] = sum/M;
}
}

int  main()
{
/* inputting
float *array = new float[N*M];
/* stores the mean of the columns */
float *mean = new float[M];

//Intializing the array.
for(int i=0;i<N;i++)
{
for(int j=0;j<M;j++)
{
array[i*N+j] = (float)(i+j);
}
}

Compute_Mean(array,mean);

}


##### Share on other sites
You are initializing the values in your matrix incorrectly:
array[i*N+j] = (float)(i+j);

should be
array[i*M+j] = (float)(i+j);

##### Share on other sites
You are confusing M and N; why not call them NUMBER_OF_ROWS and NUMBER_OF_COLUMNS, and declare them as const int instead of using dangerous macros?

mean[i] sould be sum/N (divide by the length of the inner loop), and the index in printf is wrong as well.

##### Share on other sites

This topic is 3377 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628703
• Total Posts
2984301

• 23
• 10
• 9
• 13
• 13