1

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 Answers1

1

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)
sehe
  • 374,641
  • 47
  • 450
  • 633
  • hey, thank you very much! I tried that but it didn't work the first time because I didn't include assignment header file. – nino dragičević Jan 01 '23 at 17:04
  • To further expand my question, now i need to find the inverse of the mentioned m1 matrix. Do you maybe know if boost uBLAS has a function for that? I don't see it in the docs? – nino dragičević Jan 01 '23 at 17:50
  • You're welcome to ask separate questions. This is a Q&A site, not a forum or support site. This what I remember https://stackoverflow.com/a/65995217/85371 but keep in mind this comment https://stackoverflow.com/questions/73790439/eigen-and-boost-matrix-inversions-give-different-results#comment130318133_73790439 - often you should avoid calculating the inverse altogether – sehe Jan 01 '23 at 19:34