Boost logo

Ublas :

From: Vardan Akopian (vakopian_at_[hidden])
Date: 2007-07-17 02:40:55

On 7/11/07, Nico Galoppo <nico_at_[hidden]> wrote:
> Hi,
> what is the best way to construct a diagonal matrix from a vector (where the
> vector should be the diagonal).
> I think I can use banded_matrix<> for diagonal matrices, but there seems to be
> no explicit constructors except for maybe assigning the vector to a slice of the
> banded_matrix<>? In this case, what are the performance implications?

diagonal_matrix (which is in banded.hpp) has a constructor which takes
the storage array as an argument. You could use that and copy the data
from your vector into the diagonal matrix. E.g.

vector<double> v; // your vector containing the diagonal elements
diagonal_matrix<double> diagMatrix(v.size(),;

If you need to share the data between the vector and the diagonal
matrix, that's also possible, but not very straightforward (nor safe).
If you are careful with it (see ), you can
use the shallow_array_adaptor to represent the vector as a diagonal
matrix. Do read the link above, and make sure that all the potential
issues Gunter pointed out are ok in your application. If it's all ok,
here is how you would do it:

vector<double> v; // your vector containing the diagonal elements
shallow_array_adaptor<double> share(v.size(),;
diagonal_matrix<double, row_major, shallow_array_adaptor<double> >
diagMatrix(v.size(), share);

Note that this will only work for dense vectors.