rust 使用nalgebras执行基本运算最通用的矩阵类型

ymdaylpp  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(95)

我试图弄清楚如何编写以通用nalgebra矩阵和向量作为参数并对其执行基本操作的函数,我对固定大小和动态大小的矩阵的通用性特别感兴趣。
例如,下面的函数应该接受SVectorDVector参数并减去它们:

use nalgebra::{DVector, Matrix, U1, Dim, RawStorage, Storage};

fn function<R, S>(a: &Matrix<f64, R, U1, S>, b: &Matrix<f64, R, U1, S>)
    where R: Dim, S: RawStorage<f64, R> + Storage<f64, R>
{
    let c = b - a;
}

fn main() {
    let a = DVector::<f64>::zeros(3);
    let b = DVector::<f64>::zeros(3);
    function(&a, &b);
    
    let a = SVector::<f64, 3>::zeros();
    let b = SVector::<f64, 3>::zeros();
    function(&a, &b);
}

字符串
但是,减法不起作用,并导致以下错误:

error[E0369]: cannot subtract `&Matrix<f64, R, Const<1>, S>` from `&Matrix<f64, R, Const<1>, S>`
 --> src/main.rs:6:15
  |
6 |     let c = b - a;
  |             - ^ - &Matrix<f64, R, Const<1>, S>
  |             |
  |             &Matrix<f64, R, Const<1>, S>
  |
help: consider extending the `where` clause, but there might be an alternative better way to express this requirement
  |
4 |     where R: Dim, S: RawStorage<f64, R> + Storage<f64, R>, DefaultAllocator: nalgebra::allocator::Allocator<f64, R>
  |                                                          ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

For more information about this error, try `rustc --explain E0369`.


我不确定是否可以像编译器建议的那样,通过添加更多的trait边界来解决这个问题,或者Matrix类型根本不支持这些操作。

w6mmgewl

w6mmgewl1#

编译器建议的边界将起作用(这就是它首先建议它的原因),但在这种情况下,我会遵循代码的字面要求,而不是对所需trait的实现的模糊边界(这里是Sub):

use nalgebra::{DVector, Matrix, U1, Dim, RawStorage, Storage, SVector};

fn function<'a, R, S>(a: &'a Matrix<f64, R, U1, S>, b: &'a Matrix<f64, R, U1, S>)
where
    R: Dim,
    S: RawStorage<f64, R> + Storage<f64, R>,
    &'a Matrix<f64, R, U1, S>: std::ops::Sub<&'a Matrix<f64, R, U1, S>>,
{
    let c = b - a;
}

fn main() {
    let a = DVector::::zeros(3);
    let b = DVector::::zeros(3);
    function(&a, &b);
    
    let a = SVector::::zeros();
    let b = SVector::::zeros();
    function(&a, &b);
}

字符串
而且它的工作原理和预期的一样。
Playground

相关问题