1
\$\begingroup\$

I'm implementing a CSR and CSC class! I found a lot of algorithms for computing a CSC * vector product but I didn't find any routine for the CsC * CsC matrix product, in order to save time when the size of the matrix becomes very large !

So I used the classical way of product ... in order to do this I have implemented operator()(i,j) that returns a value if it is different from zero, otherwise zero. For doing so I wrote a findindex utility function as follow :

template<typename T>
inline auto CSCmatrix<T>::findIndex(const std::size_t row, const std::size_t col) const noexcept
{
    auto ijt = std::find(ia_.begin()+ja_.at(col) , ia_.begin()+ja_.at(col+1), row );  

    return static_cast<std::size_t>(std::distance(ia_.begin(), ijt ) );

}

//
// operator ()
template<typename T>
inline const T CSCmatrix<T>::operator()(const itype row,const itype col)const noexcept  
{
    const auto i = findIndex(row,col);  

    if(i < ja_.at(col+1))
      return a_.at(i) ;
    else 
      return 0.0 ;
}

using this expansive operator .. I've implemented the product as follow :

template<typename T>
CSCmatrix<T> operator*(const CSCmatrix<T>& m1, const CSCmatrix<T>& m2) 
{

      if( m1.size2() != m2.size1() )
      {
          throw std::runtime_error("Exception in operator * :  Matrix dimension must agree !"); 
      }

      CSCmatrix<T> res(m1.size1(), m2.size2());
      double sum ;
      for(std::size_t i=0 ; i < res.size1() ; i++ )   // 
      {            
            for(std::size_t j=0; j< res.size2() ; j++ )
            {     
                  sum = 0;
                  for(std::size_t k=0; k< m1.size2() ; k++ )
                  {
                     sum += m1(i,k)*m2(k,j) ;
                  }
                  res(i,j,sum);
            }
      }      
      return res;

}

I am looking for a way to improve my code. What can I do?

\$\endgroup\$
  • \$\begingroup\$ You should include the whole code of CSCmatrix if you want a decent review. Otherwise it's hard to tell what your code does. For example, I suspect that the line res(i,j,sum); is an assignment statement, but without the definition of CSCmatrix::operator()(size_t,size_t,double), it's impossible to be sure. (And yes, this is a mini-review of the readability of your code. ;)) \$\endgroup\$ – Quuxplusone Jan 24 '18 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.