How to assign the column of one matrix to another, nalgebra?

108 views Asked by At

I am using nalgebra and I want to modify one matrix by setting it as the columns of another with compatible dimensions, like this:

    let zero: T = convert(0.0);
    let mut basis = DMatrix::from_element(rows, rank, zero);
    // matrix is an input with dimensions rows x cols
    for i in 0..location.len()
    {
        basis.column_mut(i) = matrix.column(location[i]);
    }

I have also tried dereferencing both sides of the assignment and looked for an "assign" method of some kind, no luck.

set_column doesn't work because DMatrix does not implement DimName

My current work around is this, but I don;t like it one bit:

 // Construct basis vectors initialized to 0.
    let zero: T = convert(0.0);
    let mut basis = DMatrix::from_element(rows, rank, zero);

    for i in 0..location.len()
    {
        // Copy the pivot column from the matrix.
        let col = location[i];
        for r in 0..matrix.nrows()
        {
            basis[(r, i)] = matrix[(r, col)];
        }
    }
1

There are 1 answers

0
mcmuffin6o On BEST ANSWER

I don't know what column_mut means, what it does, or how it's supposed to work, either. The documentation for it is fairly sparse (nonexistent). I think set_column does what you're trying to do (perhaps you called it incorrectly?):

use nalgebra::DMatrix;
let rows = 2;
let cols = 3;
let zero = 0.0;
let mut basis = DMatrix::from_element(rows, cols, zero);
let matrix = DMatrix::from_row_slice(rows, cols, &[
  1.0, 3.0, 5.0,
  2.0, 4.0, 6.0
]);
let location = [1, 0, 2];
for i in 0..location.len() {
  basis.set_column(i, &matrix.column(location[i]));
}

(I tweaked your code to be an MWE)