matrixrustmatrix-multiplicationbroadcastnalgebra

How does the Rust nalgebra crate implement broadcast operations on matrix?


I'm learning to use the nalgebra library and the problem I'm having is: how to add, subtract, multiply, divide a number for each element in a matrix?

Say I have a 2x3 matrix which has i32 elements:

extern crate nalgebra as na;

use na::*;

fn main() {
    let a = SMatrix::<i32, 3, 2>::from([[1, 2, 3], [4, 5, 6]]).transpose();
    let b: i32 = 10;

    let c = a + b;
}

The compile error in Rust playground is:

   Compiling playground v0.0.1 (/playground)
error[E0277]: cannot add `i32` to `Matrix<i32, Const<2>, Const<3>, ArrayStorage<i32, 2, 3>>`
 --> src/main.rs:9:15
  |
9 |     let c = a + b;
  |               ^ no implementation for `Matrix<i32, Const<2>, Const<3>, ArrayStorage<i32, 2, 3>> + i32`
  |
  = help: the trait `Add<i32>` is not implemented for `Matrix<i32, Const<2>, Const<3>, ArrayStorage<i32, 2, 3>>`
  = help: the following other types implement trait `Add<Rhs>`:
            <&'a Matrix<T, R1, C1, SA> as Add<&'b Matrix<T, R2, C2, SB>>>
            <&'a Matrix<T, R1, C1, SA> as Add<Matrix<T, R2, C2, SB>>>
            <Matrix<T, R1, C1, SA> as Add<&'b Matrix<T, R2, C2, SB>>>
            <Matrix<T, R1, C1, SA> as Add<Matrix<T, R2, C2, SB>>>

For more information about this error, try `rustc --explain E0277`.
error: could not compile `playground` due to previous error

Can someone tell me the reason is that nalgebra doesn't have a Broadcast feature or I don't know the right way?


Solution

  • For addition and subtraction, use add_scalar. For multiplication and division, use their respective operators.

    fn main() {
        let a = SMatrix::<i32, 3, 2>::from([[1, 2, 3], [4, 5, 6]]).transpose();
        let b: i32 = 10;
    
        let added = a.add_scalar(b);
        let subtracted = a.add_scalar(-b);
        let multiplied = a * b;
        let divided = a / b;
        
        println!("{}", added);
        println!("{}", subtracted);
        println!("{}", multiplied);
        println!("{}", divided);
    }