Boost logo

Ublas :

From: Nizar Khalifa Sallem (nksallem_at_[hidden])
Date: 2008-08-13 13:26:15


James Sutherland wrote:
> I need to modify the location (column) of some elements in a sparse
> matrix. I would prefer to do this through the MatrixRow directly
> rather than using the "remove_element" and "insert_element" functions
> on the matrix.
>
> I would like to do something like:
>
> typedef compressed_matrix< double, row_major > MatType;
> MatType m( nrow, ncol, nonzeros );
>
> // ... build matrix m ...
>
> matrix_row<MatType> row( m, irow );
> row(3).index() = 1; // move column 3 to column 1.
>
> Of course I cannot do this directly since the index() method returns a
> value, not a reference. Is there another way to accomplish this using
> a matrix_row object?
>
> James
> _______________________________________________
> ublas mailing list
> ublas_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/ublas
First of all, here you will modify rows not columns.

Second, the easy dirty way is to do something like :
  ublas::vector tmpRow = matrix_row<MatType> row( m, 1 );
  matrix_row<MatType> row( m, 1 ) = matrix_row<MatType> row( m, 3 );
  matrix_row<MatType> row( m, 3 ) = tmpRow;

Finally, you may use iterators (you need to check for consistency):
  ublas::compressed_matrix<double>::iterator1 srcRowIt, dstRowIt
  ublas::compressed_matrix<double>::iterator2 src_ij, dst_ij, tmp_ij;
    dstRowIt = srcRowIt = m.begin1();//iterator over row 0
  ++srcRowIt;//here will iterate over row 1;
    dstRowIt+=3;//iterate over row 3;
      for (src_ij = srcRowIt.begin(), dst_ij = dstRowIt.begin();
             src_ij != srcRowIt.end();
             ++src_ij,++dst_ij) {
          tmp_ij = src_ij;
          src_ij = dst_ij;
          dst_ij = tmp_ij;
          // if you do something like src_ij = dst_ij; you will loose
your row 1 elements'
      }

I didn't check this code, if you want columns just invert iterator1 and
iterator 2

Regards,