Sign in to follow this  

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this