Boost logo

Ublas :

Subject: Re: [ublas] vector< vector< T > > to matrix < T > assignment
From: Marco Guazzone (marco.guazzone_at_[hidden])
Date: 2010-09-11 09:07:50


On Fri, Sep 10, 2010 at 5:08 PM, Matwey V. Kornilov
<matwey.kornilov_at_[hidden]> wrote:
>
> Hi,
>
> How to assign vector< vector< > > to matrix < > ?
>

Hello,

Obviously, you can always iterate through each element of the outer
and inner vectors and assign each element to your matrix.

If you want something less boring you can iterate only the outer
vector and assign each inner vector to a column or a row of your
matrix.

For instance, supposing each inner vector represents a column of your
matrix, you can do the following:

--- [code] ---
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <cstddef>
#include <iostream>

namespace ublas = boost::numeric::ublas;

int main()
{
    typedef double value_type;
    typedef ublas::vector<value_type> in_vector_type;
    typedef ublas::vector<in_vector_type> out_vector_type;
    typedef ublas::matrix<value_type> matrix_type;

    const std::size_t m = 3;
    const std::size_t n = 2;

    // vector-of-vector creation
    out_vector_type vv(m);
    vv(0) = in_vector_type(n);
    vv(0)(0) = 1; vv(0)(1) = 2;
    vv(1) = in_vector_type(n);
    vv(1)(0) = 3; vv(1)(1) = 4;
    vv(2) = in_vector_type(n);
    vv(2)(0) = 5; vv(2)(1) = 5;

    // matrix creation: each inner vector is a column of the matrix
    matrix_type M(n,m);
    for (std::size_t c = 0; c < m; ++c)
    {
        ublas::column(M, c) = vv(c);
    }

    std::cout << "M = " << M << std::endl;
}
--- [/code] ---

Tested with GCC 4.4.4: g++ -Wall -Wextra -ansi -pedantic

If each inner vector may have a different size, then is your
responsibility to ensure that your matrix has a number of columns
large enough to contain the longest inner vector.
If you don't know in advance the size of each inner vector, you can
iterator the outer vector in order to find the max size, e.g.:

--- [code-snip] ---
// Find the max inner vector size
std::size_t m = 0;
for (std::size_t i=0; i < vv.size(); ++i)
{
  if (m < vv(i).size())
  {
    m = vv(i).size();
  }
}
--- [/code-snip] ---

Best,

-- Marco