How to update a cell in a matrix

Hi,

I have a matrix defined as such:

     let mut A = DMatrix::from_iterator(
        observed_count,
        self.max_df_lag,
        a
        .iter()
        .cloned(),
        );

this is e.g. a 8x4 matrix with zeros;

How do change e.g. Row 2 Col 1 to value of 99?

A[1][0] = 99;

Thanks

Hi!

You can index by a tuple: A[(1, 0)] = 99.

Is it possible to update a whole row of a matrix?

For example,

let mut aa = Matrix3x4::new(1,2,3,4,5,6,7,8,9,10,11,12);
  ┌                ┐
  │  1  2  3  4    │
  │  5  6  7  8    │
  │  9 10 11 12    │
  └                ┘

Is it possible to do something like the following?

aa[2,:] = aa[2,:] * 2

aa = 
    ┌                 ┐
    │  1    2   3   4 │
    │  10  12  14  16 │
    │  9   10  11  12 │
    └                 ┘

If it is not possible, any work around?

Hi @ruste23!

You can do:

let mut row1 = aa.row_mut(1);
row1 *= 2;

or:

use std::ops::MulAssign;
aa.row_mut(1).mul_assign(2);

(Note that writing aa.row_mut(1) *= 2; directly will not compile.)
More generally, you may be interested in the section about matrix slicing from the user guide.

1 Like

Thanks @sebcrozet . This is what I was looking for.