pub type Matrix = nalgebra::DMatrix<f64>;
pub fn from_rows(rows: Vec<Vec<f64>>) -> Result<Matrix, String> {
if rows.is_empty() {
return Err("empty matrix".into());
}
let ncols = rows[0].len();
let nrows = rows.len();
for (i, r) in rows.iter().enumerate() {
if r.len() != ncols {
return Err(format!(
"row {} has {} cols, expected {}",
i,
r.len(),
ncols
));
}
}
let mut data = vec![0.0; nrows * ncols];
for r in 0..nrows {
for c in 0..ncols {
data[c * nrows + r] = rows[r][c];
}
}
Ok(Matrix::from_vec(nrows, ncols, data))
}
pub fn add_multiple(matrix: &Matrix, target: usize, source: usize, multiplier: f64) -> Matrix {
let mut result = matrix.clone();
let src = result.row(source).clone_owned();
let new_row = result.row(target).clone_owned() + src * multiplier;
result.set_row(target, &new_row);
result
}
pub fn multiply_row(matrix: &Matrix, target: usize, multiplier: f64) -> Matrix {
let mut result = matrix.clone();
let new_row = result.row(target).clone_owned() * multiplier;
result.set_row(target, &new_row);
result
}
pub fn replace_row(matrix: &Matrix, target: usize, source: usize) -> Matrix {
let mut result = matrix.clone();
let src = result.row(source).clone_owned();
result.set_row(target, &src);
result
}
pub fn add_multiple_col(matrix: &Matrix, target: usize, source: usize, multiplier: f64) -> Matrix {
let mut result = matrix.clone();
let src = result.column(source).clone_owned();
let new_col = result.column(target).clone_owned() + src * multiplier;
result.set_column(target, &new_col);
result
}
pub fn multiply_col(matrix: &Matrix, target: usize, multiplier: f64) -> Matrix {
let mut result = matrix.clone();
let new_col = result.column(target).clone_owned() * multiplier;
result.set_column(target, &new_col);
result
}
pub fn replace_col(matrix: &Matrix, target: usize, source: usize) -> Matrix {
let mut result = matrix.clone();
let src = result.column(source).clone_owned();
result.set_column(target, &src);
result
}