Boost logo

Boost Users :

From: Kresimir Fresl (fresl_at_[hidden])
Date: 2003-06-08 09:14:52


cerenoc wrote:

> I am trying a reasonably simple operation of
> assigning a vector v(2) to a submatrix (3,3). For example, in matlab
> notation:
> m =
> 0 1 2
> 3 4 5
> 6 7 8
> v =
> 15 16
>
> m(2, 1:2) = v
>
> resulting in:
> m =
>
> 0 1 2
> 15 16 5
> 6 7 8
>
> What is the best way to do this with ublas? [...]

========================================
#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

using std::cin;
using std::cout;
using std::endl;
namespace ublas = boost::numeric::ublas;

int main() {

   cout << endl;
   ublas::matrix<double> m;
   cout << "m -> ";
   // input is: [3,3]((0,1,2),(3,4,5),(6,7,8))
   cin >> m;
   cout << m << endl;
   cout << endl;
   ublas::vector<double> v;
   cout << "v -> ";
   // input is: [2](15,16)
   cin >> v;
   cout << v << endl;
   cout << endl;

   project (row (m, 1), ublas::range (0, 2)) = v;
   cout << endl;
   cout << m << endl;
   cout << endl;
}
========================================

Essential line is:

    project (row (m, 1), ublas::range (0, 2)) = v;

`row (m, r)' extracts r-th row (that is, row with index `r') of `m'.
Extracted row has type `matrix_row<M>' which is a subtype
of `vector_expression<E>' (which can be thought of as
a kind of a vector).

Now, to extract first and second element (i.e. elements
with indices 0 and 1) from the row, one can use
`project' function

   project (vct, ublas::range (first, beyond))

This function extracts from `vct' a vector range (with the
type `vector_range<V>') from 'first' to, but not including,
`beyond' -- this is similar to iterator ranges.

Another function which can be used is

   project (vct, ublas::slice (first, step, num))

This function forms a vector slice (type `vector_slice<V>')
with `num' elements starting at the element with index `first'
and increasing indices by `step'; e.g.

    project (vct, ublas::slice (3, 2, 4))

will form vector slice containing elements which have
indices 3,5,7,9 in `vct'. In your example, this will be

    project (row (m, 1), ublas::slice (0, 1, 2));

There are some shortcuts, too:

    m[1](ublas::range (0,2))
    m.row(1)(ublas::range (0,2))

Sincerely,

fres


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net