I am using nalgebra and trying to do the following:
Given a large dense amtrix, e.g. a 5x5. I want to grab a block of that matrix, e.e.g a 4x5 sublock, and treat that block as a matrix. I want to perform scalar multiplication and vector addition on the block and I want the result to reflect in the original matrix without performing copies.
For example:
let mat /*
initialize mat to:
┌ ┐
│ -1.9582069 -0.0063802134 -0.40666944 -23.94156 │
│ -0.39497808 -0.44723305 1.908919 -16.907166 │
│ -0.09702926 1.9493433 0.43662617 -11.965615 │
│ 0 0 -0 2 │
└ ┘
*/
let mut slice = &mat.slice((0, 0), (3, 4));
slice = slice * 0;
Should make it so that if I print mat
now the top 3 rows are zeroed out.
I have tried different combinations of parameters but I have not quite been able to get the result I want.
Currently all my attempts end in errors like this:
39 | *slice = 0.0 * slice;
| ------ ^^^^^^^^^^^ expected struct `SliceStorageMut`, found struct `VecStorage`
You are unable to write through an immutable slice like the one produced by slice
so you need to take a mutable slice of the matrix using slice_mut
. You also don't need the &
since the slice object is already a reference in itself. If you take an immutable reference to a mutable slice, it will prevent you from writing to the matrix.
// Take a slice of the matrix
let mut slice = mat.slice_mut((0, 0), (3, 4));
// Modify the slice in place
slice *= 2.0;