c++matrixcolumn-sum

How to Sum Column of a Matrix and Store it in a Vector in C++


Is there a straight forward way to do it? I'm stuck here:

#include <iostream>
#include <vector>
#include <cstdlib>

using std::size_t;
using std::vector;
int main()
{  
  vector<vector<int> > Matrix;

  //Create the 2x2 matrix.
  size_t rows = 2;
  size_t cols = 2;  
  // 1: set the number of rows.
   Matrix.resize(rows);


  for(size_t i = 0; i < rows; ++i)
  {
    Matrix[i].resize(cols);
  }

  // Create Matrix
  Matrix[0][0] = 1;
  Matrix[0][1] = 2;
  Matrix[1][0] = 3;
  Matrix[1][1] = 4;



  // Create Vector to store sum
  vector <int> ColSum;

  for(size_t i = 0; i < rows; ++i)
  {
    for(size_t j = 0; j < cols; ++j)
    {
      std::cout <<"["<<i<<"]"<<"["<<j<<"] = " <<Matrix[i][j]<<std::endl;
      // I'm stuck here

    }
  }  

  return 0;
}

Given the matrix above:

1 2 
3 4

In the end we hope to print the result of a vector (that keeps the sum of each column):

4 6

Note that the matrix can be of any dimension.


Solution

  • for( size_t row = 0; row < Matrix.size(); row++ )
    {
        ColSum[row] = 0;
        for( size_t column = 0; column < Matrix[row].size(); column++ )
        {
          ColSum[row] += Matrix[row][column];
        }
    }