# Ublas :

Subject: Re: [ublas] Howto Create Your Own Sparse Matrix by Giving RA/IA/JA Param
From: Gunter Winkler (guwi17_at_[hidden])
Date: 2009-01-28 17:27:24

Gundala Viswanath schrieb:
> Dear all,
>
> Is there a way to do it with Boost's Ublas.
>
> For example given these vectors:
>
> //Begin Assign Var
> using namespace boost::assign;
> vector <double> realValue;
> realValue +=
> 0.994704478,
> 0.989459074,
> 0.994717023,
> 1.000000000,
> 1.000000000,
> 0.002647761,
> 0.005282977,
> 0.000882587,
> 0.005270463,
> 0.000882587,
> 0.002635231,
> 0.000882587,
> 0.002635231
>
> vector<int>rowIndex;
> rowIndex += 1, 2, 3, 4, 5, 1, 3, 1, 2, 1, 2, 1, 2;
>
> vector<int>colIndex;
> colIndex += 1, 2, 3, 4 ,5, 5, 3, 2, 1, 3, 3, 4, 4;
>
> vector<int>matDim;
> matDim += 5,5; // M always equal to N
>
> One would like to create this matrix:
>
> /*
> [ 0.994704478, 0.000882587, 0.000882587, 0.000882587, 0.002647761],
> [ 0.005270463, 0.989459074, 0.002635231, 0.002635231, 0.000000000],
> [ 0.000000000, 0.000000000, 0.005282977, 0.000000000, 0.000000000].
> [ 0.000000000, 0.000000000, 0.000000000, 1.000000000, 0.000000000],
> [ 0.000000000, 0.000000000, 0.000000000, 0.000000000, 1.000000000]
> */
>
> It is simply done by assigning the value in realValue given
> the corresponding (rowIndex,colIndex) as coordinate.
> For example the value for last element in rowIndex and colIndex is
> (2,4). Hence we insert 0.002635231 in row 2 col 4 in above matrix.
>
>
>
The quickest solution is to use a

ublas::coordinate_matrix<double> m(5,5);

and fill it using

m.append_element(i,j,value);

The internal storage is exactly as given: m.index1_data(),
m.index2_data() and m.value_data() return the corresponding array.

a more compact storage schema is implemented by

compressed_matrix<double> B(5,5);

however you have to use B.insert_element(i,j,value); which is slower
(worst case O(nnz)) than coordinate_matrix::append_element(...);

mfg
Gunter