Skip to content

Instantly share code, notes, and snippets.

@lmmx
Created December 23, 2025 16:49
Show Gist options
  • Select an option

  • Save lmmx/7b0dcda14f70d09b8a0fe928f2d98543 to your computer and use it in GitHub Desktop.

Select an option

Save lmmx/7b0dcda14f70d09b8a0fe928f2d98543 to your computer and use it in GitHub Desktop.
Pure Rust SVD computation with faer
//! ```cargo
//! [dependencies]
//! faer = "0.23"
//! ```
use faer::prelude::*;
use faer::linalg::solvers::Svd;
fn main() -> Result<(), faer::linalg::solvers::SvdError> {
// 3×2 example matrix
let a = mat![
[1.0, 2.0],
[3.0, 4.0],
[5.0, 6.0],
];
println!("Original matrix A:");
print_mat_ref(a.as_ref());
// Compute full SVD
let svd = Svd::new(a.as_ref())?;
let u = svd.U();
let s = svd.S();
let vt = svd.V();
println!("\nSingular values (Σ):");
let s_col = s.column_vector();
for val in s_col.iter() {
println!("{:8.4}", val);
}
println!("\nU matrix:");
print_mat_ref(u);
println!("\nV^T matrix:");
print_mat_ref(vt);
Ok(())
}
/// Print function for MatRef
fn print_mat_ref(mat: MatRef<'_, f64>) {
let (rows, cols) = mat.shape();
for i in 0..rows {
for j in 0..cols {
print!("{:8.4} ", mat[(i, j)]);
}
println!();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment