elementary-row-operation-verifier 0.0.1

A tool to verify the correctness of elementary row operations on matrices
Documentation
pub type Matrix = nalgebra::DMatrix<f64>;

/// 从 Vec<Vec<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
            ));
        }
    }
    // nalgebra::from_vec 是列优先,需要转置
    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
}