Rust nalgebra如何实现矩阵上的广播操作?

lx0bsm1f  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在学习使用nalgebra库,我遇到的问题是:如何对矩阵中的每个元素进行加、减、乘、除运算?
假设我有一个2x3矩阵,其中包含i32个元素:

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;
}

Rust playground中的编译错误是:

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

有人能告诉我原因是nalgage没有广播功能还是我不知道正确的方法?

x33g5p2x

x33g5p2x1#

对于加法和减法,请使用add_scalar。对于乘法和除法,请使用它们各自的运算符。

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);
}

相关问题