rustnalgebra

How do I create an nalgebra static matrix by copying from a dynamic matrix view?


I'm trying to create a na::Matrix2x3 by copying from the first two rows of a na::Matrix3. The result will be stored in a struct.

I don't know how to do this and the documentation is confusing. I tried clone(), into(), from(...), etc., but nothing seems to work.

Here is a reproducible example where I have tried to use .clone() (playground):

extern crate nalgebra as na; // 0.27.1

fn main() {
    let proj33 = na::Matrix3::<f64>::zeros();
    let proj: na::Matrix2x3<f64> = proj33.rows(0, 2).clone();
}
error[E0308]: mismatched types
 --> src/main.rs:5:36
  |
5 |     let proj: na::Matrix2x3<f64> = proj33.rows(0, 2).clone();
  |               ------------------   ^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Const`, found struct `Dynamic`
  |               |
  |               expected due to this
  |
  = note: expected struct `Matrix<_, Const<2_usize>, _, ArrayStorage<f64, 2_usize, 3_usize>>`
             found struct `Matrix<_, Dynamic, _, SliceStorage<'_, f64, Dynamic, Const<3_usize>, Const<1_usize>, Const<3_usize>>>`

This seems to work, but it is wasteful as it initializes the matrix to zeros first:

let mut proj = na::Matrix2x3::<f64>::zeros();
proj.copy_from(&proj33.rows(0, 2));

In Eigen (C++) I would have done this:

const Eigen::Matrix<double, 2, 3> proj = proj33.topRows(2);

Solution

  • …or probably better suited: fixed_rows()

    let proj33 = na::Matrix2x3::<f64>::zeros();
    let proj: na::Matrix2x3<f64> = proj33.fixed_rows::<2>(0).into();