How do I fill matrices created in c++ using boost uBLAS?

293 Views Asked by At

Im new to C++ in general. I have an assignment where I need to create a 5x5 matrix with set constant values using the boost uBLAS library. I then have to multiply those matrices using boost uBLAS.

So far I have:

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

    using namespace boost::numeric::ublas;

int main()
{
    matrix<double> m1 (5, 5);
    vector<double> v1 (5);
    std::cout << m1;
    std::cout << v1;
}

So basically I created 5x5 matrix and a vector which are both filled with zeroes. How do I fill the matrix and vector with my desired numbers, so that (for example):

m1 = [2,1,4,6,3;
      8,2,0,1,4;
      7,3,2,4,7;
      1,2,0,9,3;
      2,6,4,3,1]

and

v1 = [2;
      3;
      1;
      7;
      6]
1

There are 1 best solutions below

3
On BEST ANSWER

You can use the uBlas assignment operator <<=:

#include <boost/numeric/ublas/assignment.hpp>

Then e.g.

m1 <<= 2,1,4,6,3,
       8,2,0,1,4,
       7,3,2,4,7,
       1,2,0,9,3,
       2,6,4,3,1;

v1 <<= 2,
       3,
       1,
       7,
       6;

std::cout << "m1: " << m1 << "\n";
std::cout << "v1: " << v1 << "\n";

See it Live On Coliru

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

using namespace boost::numeric::ublas;

int main() {
    matrix<double> m1(5, 5);
    vector<double> v1(5);
    std::cout << "m1: " << m1 << "\n";
    std::cout << "v1: " << v1 << "\n";

    m1 <<= 2,1,4,6,3,
           8,2,0,1,4,
           7,3,2,4,7,
           1,2,0,9,3,
           2,6,4,3,1;

    v1 <<= 2,
           3,
           1,
           7,
           6;

    std::cout << "m1: " << m1 << "\n";
    std::cout << "v1: " << v1 << "\n";
}

Prints

m1: [5,5]((0,0,0,0,0),(0,0,0,0,0),(0,0,0,0,0),(0,0,0,0,0),(0,0,0,0,0))
v1: [5](0,0,0,0,0)
m1: [5,5]((2,1,4,6,3),(8,2,0,1,4),(7,3,2,4,7),(1,2,0,9,3),(2,6,4,3,1))
v1: [5](2,3,1,7,6)