3

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?

Devil
  • 903
  • 2
  • 13
  • 21

1 Answers1

2

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);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80