Find the mean vector of a Matrix in C++

C++Server Side ProgrammingProgramming

Suppose we have a matrix of order M x N, we have to find the mean vector of the given matrix. So if the matrix is like −

123
456
789

Then the mean vector is [4, 5, 6] As the mean of each column is (1 + 4 + 7)/3 = 4, (2 + 5 + 8)/3 = 5, and (3 + 6 + 9)/3 = 6

From the example, we can easily identify that if we calculate the mean of each column will be the mean vector.

Example

 Live Demo

#include<iostream>
#define M 3
#define N 3
using namespace std;
void calculateMeanVector(int mat[M][N]) {
   cout << "[ ";
   for (int i = 0; i < M; i++) {
      double average = 0.00;
      int sum = 0;
      for (int j = 0; j < N; j++)
      sum += mat[j][i];
      average = sum / M;
      cout << average << " ";
   }
   cout << "]";
}
int main() {
   int mat[M][N] = {{ 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 }
   };
   cout << "Mean vector is: ";
   calculateMeanVector(mat);
}

Output

Mean vector is: [ 4 5 6 ]
raja
Published on 17-Dec-2019 16:34:35
Advertisements