Support for sum of matrix elements

Issue #122 duplicate
Fabien Péan
created an issue

Hi Blaze team,

It would be nice to have a function sum similar to the one of Matlab.

It could be represented as

sum<rowVector>(Matrix m) 

returning a row vector of the size of m.rows() and

sum<columnVector>(Matrix m)

returning a column vector of the size of m.columns()

A quick unoptimized solution would be to add something like below the following to blaze/math/Matrix.h

template< bool TF, typename MT, bool SO >
inline auto sum( const Matrix<MT,SO>& m )
{
  constexpr bool isRowVector = (TF == rowVector);
  const size_t ibegin = 0UL;
  const size_t iend = (~m).rows();
  const size_t jbegin = 0UL;
  const size_t jend = (~m).columns();

  using ET = ElementType_<MT>;
  DynamicVector<ET, TF> tmp((isRowVector)?jend:iend, 0);

  if (isRowVector) {
    for (size_t i = ibegin; i < iend; ++i) {
      for (size_t j = jbegin; j < jend; ++j) {
        tmp[j] += (~m)(i,j);
      }
    }
  }
  else {
    for (size_t i = ibegin; i < iend; ++i) {
      for (size_t j = jbegin; j < jend; ++j) {
        tmp[i] += (~m)(i,j);
      }
    }
  }

  return tmp;
}

However, there are certainly more efficient way to do it using blaze internals, like direct row or column summation instead of elements (below), or specialization for matrix adaptors/types by using properly templates.

  for (size_t i = ibegin; i < iend; ++i)
       tmp += row(~m, i);
  for (size_t j = jbegin; j < jend; ++j)
       tmp += column(~m, j);

Comments (5)

  1. Klaus Iglberger

    Hi Fabien!

    Thanks for your proposal. This is indeed a missing, but very important feature. Therefore we already have it on your agenda (see issue #4). We hope that we can deal with this as soon as possible and that your solution works for the time being.

    Since the idea is already captured in issue #4 we close this issue as a duplicate. Please feel free to vote for the other issue. Again, thanks a lot for your proposal,

    Best regards,

    Klaus!

  2. Log in to comment