Search code examples
c++matrixboostvectorublas

Creating boost::numeric::ublas vector from another subvector or submatrix


I am trying to create a vector from another submatrix or subvector. I have tried following but get this error error: no match for ‘operator=’

 int m_size = 10; 
 boost::numeric::ublas::matrix<double> u_a(m_size, m_size);
  boost::numeric::ublas::vector<double> u_v(m_size);

    for (int i = 0; i < m_size; i = i + 1 ){
        for (int j = 0; j < m_size; j++ ){
         double rand1 = (rand()%10+1) +  ((double) rand() / (RAND_MAX));
         u_a(i,j) = rand1;
    }
    double rand3 = (rand()%10+1) +  ((double) rand() / (RAND_MAX));
    u_v(i) = rand3;
    }

for (int i = 0; i < m_size; i = i + 1 ){
  boost::numeric::ublas::matrix<double> u_p(i, i);
  boost::numeric::ublas::vector<double> u_v2(i);
  u_p = subrange(u_a, 0, i, 0, i); 
  // I have tried following two   
  //u_v2 = subrange(u_a, 0,1,0,5);
  //u_v2 = subrange(u_v, 1,i); 
 }

Solution

  • The issue with this line:

    u_v2 = subrange(u_a, 0,1,0,5);
    

    is that the subrange of a matrix is a matrix expression, not a vector expression, and you are assigning to a vector. You can use the row() free function to perform the desired conversion:

    u_v2 = row(subrange(u_a, 0, 1, 0, 5), 0);
    

    This line:

    u_v2 = subrange(u_v, 1,i); 
    

    compiles fine, but fails with a runtime error. This is because on the initial iteration, the requested range goes from 1 to 0 which is invalid. If you wanted the subvector of i - 1 elements starting at index 1, you would do it like this:

    u_v2 = subrange(u_v, 1, 1 + i); 
    

    Live at CoLiRu