rust

Diagonal matrix from vector


Using faer crate, I'm trying to create a diagonal matrix from a vector:

use faer::{Mat}

fn foo(
  vector: &[f64],
) -> Mat<f64> {

  // convert inputs to faer matrix
  let vector_faer = Mat::from_fn(1, vector.len(), |_, col| vector[col]);
  
  Mat::column_vector_as_diagonal(&vector_faer);

Despite rust-analyzer doesn't shows any warning, it panics (see below for n = 5). What am I missing?

Assertion failed: self.ncols() == 1
- self.ncols() = 5
- 1 = 1

Solution

  • Turns out I was trying to use Mat::column_vector_as_diagonal() with a row vector instead of a column vector. Correct would be

    // convert inputs to faer matrix
      let vector_faer = Mat::from_fn(vector.len(), 1, |row, _| vector[row]);