Is there a preferred way to create a matrix from a vector?

Issue #135 resolved
Parsa Amini created an issue

I don't see, say a DynamicMatrix constructor that accepts a dense vector, or something similar. Obviously, I can iterate over the elements of a vector to fill a matrix, but is there a better way of doing this?

Comments (4)

  1. Klaus Iglberger

    Hi!

    Thanks for creating this proposal. There is indeed no matrix constructor that accepts a vector. The preferred way to convert between vectors and matrices is via the row() and column() views:

    DynamicMatrix<int> A( 3UL, 5UL );                    // Creating a 3x5 matrix
    DynamicVector<int,rowVector>    a{ 1, 2, 3, 4, 5 };  // Creating a row vector
    DynamicVector<int,columnVector> b{ 1, 2, 3 };        // Creating a column vector
    
    row   ( A, 1UL ) = a;  // Assigning the row vector to the 1st row of A
    column( A, 2UL ) = b;  // Assigning the column vector to the 2nd column of A
    
    a = row   ( A, 2UL );  // Assigning the 2nd row of A to the row vector
    b = column( A, 3UL );  // Assigning the 3rd column of A to the column vector
    

    Please note that the interface distinguishes between row vectors and column vectors. The attempt to assign a row vector to a column vector or vice versa results in a compilation error.

    The feature to assign a vector to all rows or all columns of a matrix is unfortunately not available yet, but has already been requested in issue #43. For now, the following two functions might help you:

    template< typename MT, typename VT >
    void fill( MT& matrix, const Vector<VT,columnVector>& vector )
    {
       for( size_t j=0UL; j<matrix.columns(); ++j ) {
          column( matrix, j ) = ~vector;
       }
    }
    
    template< typename MT, typename VT >
    void fill( MT& matrix, const Vector<VT,rowVector>& vector )
    {
       for( size_t j=0UL; j<matrix.rows(); ++j ) {
          row( matrix, j ) = ~vector;
       }
    }
    

    If you pass a row vector to the fill() function, then it is assigned to all rows of the matrix, if you pass a column vector, it will be assigned to all columns of the matrix.

    Hopefully this solves the problem.

    Best regards,

    Klaus!


    Edit: As the matrix is a 3x5 matrix, the row vector a needs to be a vector with 5 elements and the column vector b needs to be a vector with 3 elements.

  2. Log in to comment