0

Does anyone no a simple way to get the inverse of a matrix using the Rust nalgebra::Matrix ? I'm trying to do this the same way as with the C++ Eigen library but clearly not working.

#cargo.toml

[dependencies]
nalgebra = "0.30"

#main.rs

let mut m = Matrix3::new(11, 12, 13,
                    21, 22, 23,
                    31, 32, 33);    

println!("{}", m);
println!("{}", m.transpose());
println!("{}", m.inverse()); // This blows up  
sbeskur
  • 2,260
  • 23
  • 23

1 Answers1

1

Nalgebra's Matrix does not have a straight-up inverse method, mainly because matrix inversion is a fallible operation. In fact, the example matrix doesn't even have an inverse. However, you can use the try_inverse method:

let inverse = m.try_inverse().unwrap();

You can also use the pseudo_inverse method if that's better for your usecase:

let pseudo_inverse = m.pseudo_inverse().unwrap();

Note that the pseudoinverse is unlikely to fail, see nalgebra::linalg::SVD if you want more fine-grained control of the process.

Another note is that you have a matrix of integers, and you need a matrix of floats, although that's an easy fix- just add some decimal points:

let m = Matrix3::new(11.0, 12.0, 13.0, 21.0, 22.0, 23.0, 31.0, 32.0, 33.0);

Playground

Aiden4
  • 2,504
  • 1
  • 7
  • 24
  • Thank you for the response. I saw try_inverse() but this does not seem to work even in your playground? ^^^^^^^^^^^ method cannot be called on `Matrix<{integer}, ...` due to unsatisfied trait bounds – sbeskur Jan 18 '22 at 14:04
  • 1
    @sbeskur you can't invert a matrix of integers, you need to use a matrix of floats. See the note at the bottom of my answer. – Aiden4 Jan 18 '22 at 14:09
  • totally missed it. Thanks man. – sbeskur Jan 18 '22 at 15:01