How to update a matrix block

Hi,
Let’s suppose that I have a matrix like the following
let matrix = DMatrix::<f64>::zeros(10, 10);
I would like to update some part of the matrix in a very similar way of Eigen blocks. For instance, the upper right corner of the matrix.How can I do that in nalgebra?
Also, I know that there are the set_column and set_row methods, but I am wondering if I can make a mutable slice of a matrix and replace it with something else. I have tried the following code but it does not work and I still don’t understand why

let mut matrix = DMatrix::<f64>::zeros(10, 10);
let mut slice = matrix.index_mut((.., ..2));
let arr = DMatrix::<f64>::zeros(10, 2);
slice = arr;

Thanks for your help!

Hi!

The slice = arr; assignation cannot work because of the way assignation works in Rust. In C++, the = operator can be overloaded to make the assignation work even if both types on the right and left hand side are not the same. In Rust this overload is not possible.

Here slice is a matrix slice and arr is a plain matrix, so you can’t make this assignation because of mismatching types. Instead you can do slice.copy_from(&arr) to achieve the expected result.

Also note that the example you provided can be simplified to:

let mut matrix = DMatrix::<f64>::zeros(10, 10);
let mut slice = matrix.index_mut((.., ..2));
slice.fill(0.0);

Any modification of the components of slice will have a repercussion on the corresponding component of matrix.

Now I got it, thanks for your nice and clear explanation!