Boost logo

Ublas :

From: Paul C. Leopardi (paul.leopardi_at_[hidden])
Date: 2007-09-03 11:31:59


On Tue, 4 Sep 2007, Regis Behmo wrote:
> Hello everyone again,
> How would you iterate over the i-th row or the j-th column of a
> mapped_matrix or a compressed_matrix? I got the feeling it's not possible
> to do it in a proper (i.e: optimal) way.
>
> In the case of a simple matrix, I would do something like this:
>
> iterator1 it1 = this->begin1();
> for( int x = 0; x < i; x++ )
> it1++;
> iterator it2 = it1.begin();
>
> Is this adequate?
>
> Régis

Hi Regis,
What is i? Why does your loop not check it1 != this->end1()?
What will you be using x for?

Following is an example from GluCat which apparently works for both dense and
compressed matrices.
Best, Paul

  /// Kronecker tensor product of matrices - as per Matlab kron
  template< typename LHS_T, typename RHS_T >
  const
  RHS_T
  kron(const LHS_T& lhs, const RHS_T& rhs)
  {
    typedef RHS_T matrix_t;
    typedef typename matrix_t::size_type matrix_index_t;
    const matrix_index_t rhs_s1 = rhs.size1();
    const matrix_index_t rhs_s2 = rhs.size2();
    matrix_t result(lhs.size1()*rhs_s1, lhs.size2()*rhs_s2);
    result.clear();
    typedef typename matrix_t::value_type Scalar_T;
    typedef typename LHS_T::const_iterator1 lhs_const_iterator1;
    typedef typename LHS_T::const_iterator2 lhs_const_iterator2;
    typedef typename RHS_T::const_iterator1 rhs_const_iterator1;
    typedef typename RHS_T::const_iterator2 rhs_const_iterator2;
    for (lhs_const_iterator1
        lhs_it1 = lhs.begin1();
        lhs_it1 != lhs.end1();
        ++lhs_it1)
      for (lhs_const_iterator2
          lhs_it2 = lhs_it1.begin();
          lhs_it2 != lhs_it1.end();
          ++lhs_it2)
      {
        const matrix_index_t start1 = rhs_s1 * lhs_it2.index1();
        const matrix_index_t start2 = rhs_s2 * lhs_it2.index2();
        const Scalar_T& lhs_val = (*lhs_it2);
        for (rhs_const_iterator1
            rhs_it1 = rhs.begin1();
            rhs_it1 != rhs.end1();
            ++rhs_it1)
          for (rhs_const_iterator2
              rhs_it2 = rhs_it1.begin();
              rhs_it2 != rhs_it1.end();
              ++rhs_it2)
            result(start1 + rhs_it2.index1(), start2 + rhs_it2.index2()) =
              lhs_val * *rhs_it2;
      }
    return result;
  }