rustrust-ndarray

Updating a row of a matrix in rust ndarray


I was looking to update a row of 2D matrix in rust ndarray, but row_mut does not seem to allow me to update the row directly.

For example (playground link)

let mut array = array![[1., 2.], [3., 4.]];
let y = array![5., 5.];
array.row_mut(0) += &y;

However it works if I assign the mutable slice to a temporary variable and then do the += operation. the the following code works as expected (playground link).

let mut array = array![[1., 2.], [3., 4.]];
let y = array![5., 5.];
let mut z = array.row_mut(0);
z += &y;

Any idea what is causing the behaviour?


Solution

  • The left hand side of a compound assignment expression must be a place expression.

    A place expression is an expression that represents a memory location. These expressions are paths which refer to local variables, static variables, dereferences (*expr), array indexing expressions (expr[expr]), field references (expr.f) and parenthesized place expressions. All other expressions are value expressions.

    array.row_mut(0) is not a place expression, so += does not work. You could instead directly call add_assign.

    array.row_mut(0).add_assign(&y);