#ifndef STAN_MATH_REV_MAT_FUN_SUM_HPP #define STAN_MATH_REV_MAT_FUN_SUM_HPP #include #include #include #include namespace stan { namespace math { /** * Class for representing sums with constructors for Eigen. * The chain() method and member variables are * managed by the superclass sum_v_vari. */ class sum_eigen_v_vari : public sum_v_vari { protected: template inline static double sum_of_val(const Eigen::DenseBase& v) { double result = 0; for (int i = 0; i < v.size(); i++) result += v(i).vi_->val_; return result; } public: template explicit sum_eigen_v_vari(const Eigen::Matrix& v1) : sum_v_vari( sum_of_val(v1), reinterpret_cast(ChainableStack::instance().memalloc_.alloc( v1.size() * sizeof(vari*))), v1.size()) { for (size_t i = 0; i < length_; i++) v_[i] = v1(i).vi_; } }; /** * Returns the sum of the coefficients of the specified * matrix, column vector or row vector. * * @tparam R Row type for matrix. * @tparam C Column type for matrix. * @param m Specified matrix or vector. * @return Sum of coefficients of matrix. */ template inline var sum(const Eigen::Matrix& m) { if (m.size() == 0) return 0.0; return var(new sum_eigen_v_vari(m)); } } // namespace math } // namespace stan #endif