Skip to content

Commit

Permalink
first version of mgs #8
Browse files Browse the repository at this point in the history
  • Loading branch information
felipeZ committed Feb 16, 2020
1 parent cbe9789 commit c83b1f1
Showing 1 changed file with 26 additions and 6 deletions.
32 changes: 26 additions & 6 deletions src/modified_gram_schmidt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ on computers.
*/

extern crate nalgebra as na;
use na::DMatrix;
use na::{DMatrix, DVector, DVectorSlice};

pub struct MGS {
pub basis: DMatrix<f64>,
Expand All @@ -19,15 +19,36 @@ impl MGS {
/// The new static method takes a single argument:
/// * `vectors` to diagonalize as columns of the matrix
pub fn new(vectors: DMatrix<f64>) -> Result<Self, &'static str> {
let mut result = Err("Something when wrong!");
result
if !vectors.is_square() {
return Err("vectors must be an square matrix");
}
let dim = vectors.nrows();
let mut basis = DMatrix::<f64>::zeros(dim, dim);
// first vector of the basis
let first = vectors.column(0) / vectors.column(0).norm();
basis.set_column(0, &first);
// Iterate over the rest of the columns
for i in 1..basis.ncols() {
basis.set_column(i, &vectors.column(i));
for j in 0..i {
let proj = MGS::project(&basis.column(j), &basis.column(i));
basis.set_column(i, &(basis.column(i) - proj));
}
basis.set_column(i, &basis.column(i).normalize());
}
Ok(MGS { basis })
}

// Project
fn project(v1: &DVectorSlice<f64>, v2: &DVectorSlice<f64>) -> DVector<f64> {
let magnitud = v1.dot(&v2) / v1.dot(&v1);
return v1 * magnitud;
}
}

#[cfg(test)]
mod test {
extern crate nalgebra as na;
use approx::relative_eq;
use na::DMatrix;

#[test]
Expand All @@ -41,7 +62,6 @@ mod test {
};

let result = basis.transpose() * &basis;
let diag = result.sum();
assert!(relative_eq!(diag, dim as f64, epsilon = 1e-8));
assert!(result.is_identity(1e-8));
}
}

0 comments on commit c83b1f1

Please sign in to comment.