How to sum row vector to every row in a matrix?

Hi,

I could not find in the documentation how to sum a row vector to every row in a matrix.

Here is a naive implementation of what I would like to achieve:

let my_matrix = DMatrix::from_row_slice(2, 2, &[
    1.0, 2.0,
    3.0, 4.0
]);

let my_vector = DVector::from_row_slice(&[10.0, 20.0]);

//Naive implementation. Can this be improved?
let mut result = DMatrix::zeros(my_matrix.nrows(), my_matrix.ncols());
for row in 0..my_matrix.nrows() {
    for col in 0..my_matrix.ncols() {
        result[(row, col)] = my_matrix[(row, col)] + my_vector[col];
    }
}

let expected_result = DMatrix::from_row_slice(2, 2, &[
    11.0, 22.0,
    13.0, 24.0
]);

assert_eq!(expected_result, result);

Thanks in advance!

Hi!

There is no dedicated method for this. I think the most efficient way of doing this is the following:

let mut result = my_matrix.clone();
for (mut column, coeff) in result.column_iter_mut().zip(my_vector.iter()) {
   column.add_scalar_mut(*coeff)
}

Note that this iterates on the columns instead of on the rows. This will be much more efficient because nalgebra matrices are stored in column-major order.

Also keep in mind that if you are using matrices or vectors of small dimensions known at compile-time (like 2x2 in your example), you may use the stack-allocated types like Vector2 or Matrix2 which will generally be much more efficient than DMatrix.

Thank you @sebcrozet for the clear answer!