Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Nonanti/mathcore/llms.txt

Use this file to discover all available pages before exploring further.

The mathcore::matrix module exposes two primary types: SymbolicMatrix, a row-major matrix whose cells hold Expr nodes and thus support fully symbolic arithmetic, and LinearAlgebra, a namespace of numerical linear-algebra routines backed by the nalgebra crate. Together they cover construction, element access, addition, multiplication, transposition, determinant computation, eigenvalue analysis, LU/QR/SVD decompositions, and linear system solving.

pub struct SymbolicMatrix

A two-dimensional matrix storing Expr values. Dimensions are fixed at construction time; operations that require matching or compatible dimensions return Err(MathError::InvalidOperation) on mismatch.
#[derive(Debug, Clone)]
pub struct SymbolicMatrix {
    rows: usize,
    cols: usize,
    data: Vec<Vec<Expr>>,
}

new

Creates a zero-initialised matrix of the given dimensions. Every cell is set to Expr::zero().
pub fn new(rows: usize, cols: usize) -> SymbolicMatrix
rows
usize
required
Number of rows.
cols
usize
required
Number of columns.
use mathcore::matrix::SymbolicMatrix;

let m = SymbolicMatrix::new(3, 4); // 3×4 zero matrix

from_vec

Constructs a SymbolicMatrix from a nested Vec<Vec<f64>>. Each inner f64 value is wrapped in Expr::Number. Returns an error if the outer vector is empty or any row has an inconsistent length.
pub fn from_vec(data: Vec<Vec<f64>>) -> Result<SymbolicMatrix, MathError>
data
Vec<Vec<f64>>
required
Outer vector represents rows; each inner vector represents columns. All inner vectors must have the same length.
Returns Ok(SymbolicMatrix) or Err(MathError::InvalidOperation) for an empty or jagged input.
use mathcore::matrix::SymbolicMatrix;

let m = SymbolicMatrix::from_vec(vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0],
]).unwrap();

identity

Creates the size × size identity matrix with Expr::one() on the diagonal and Expr::zero() elsewhere.
pub fn identity(size: usize) -> SymbolicMatrix
size
usize
required
The dimension of the square identity matrix.
use mathcore::matrix::SymbolicMatrix;

let i3 = SymbolicMatrix::identity(3); // 3×3 identity

get

Returns an immutable reference to the Expr stored at (row, col), or None when the indices are out of bounds.
pub fn get(&self, row: usize, col: usize) -> Option<&Expr>
row
usize
required
Zero-based row index.
col
usize
required
Zero-based column index.

set

Writes value into cell (row, col). Returns Err(MathError::InvalidOperation) when either index is out of bounds.
pub fn set(&mut self, row: usize, col: usize, value: Expr) -> Result<(), MathError>
row
usize
required
Zero-based row index.
col
usize
required
Zero-based column index.
value
Expr
required
The symbolic expression to store in the cell.
use mathcore::matrix::SymbolicMatrix;
use mathcore::parser::Parser;
use mathcore::types::Expr;

let mut m = SymbolicMatrix::new(2, 2);
let expr = Parser::parse("x^2 + 1").unwrap();
m.set(0, 0, expr).unwrap();

if let Some(cell) = m.get(0, 0) {
    println!("{}", cell);
}

add

Element-wise symbolic addition of two matrices. Both matrices must have the same dimensions.
pub fn add(&self, other: &SymbolicMatrix) -> Result<SymbolicMatrix, MathError>
other
&SymbolicMatrix
required
The matrix to add. Must have the same number of rows and columns as self.
Returns Ok(SymbolicMatrix) with each cell holding an Expr::Binary { op: Add, .. } node, or Err(MathError::InvalidOperation) on dimension mismatch.

multiply

Symbolic matrix multiplication. Requires self.cols == other.rows.
pub fn multiply(&self, other: &SymbolicMatrix) -> Result<SymbolicMatrix, MathError>
other
&SymbolicMatrix
required
The right-hand matrix. Its row count must equal the column count of self.
Returns Ok(SymbolicMatrix) of dimension self.rows × other.cols, or Err(MathError::InvalidOperation) on incompatible dimensions.
use mathcore::matrix::SymbolicMatrix;

let a = SymbolicMatrix::from_vec(vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0],
]).unwrap();
let b = SymbolicMatrix::from_vec(vec![
    vec![5.0, 6.0],
    vec![7.0, 8.0],
]).unwrap();
let c = a.multiply(&b).unwrap();
println!("{}", c);

transpose

Returns a new matrix that is the transpose of self. For an m × n matrix the result is n × m.
pub fn transpose(&self) -> SymbolicMatrix

determinant

Computes the symbolic determinant via cofactor expansion along the first row. Requires a square matrix. For a 1×1 matrix the single element is returned; for 2×2 the standard ad - bc formula is used; larger matrices recurse using the minor sub-matrix.
pub fn determinant(&self) -> Result<Expr, MathError>
Returns Ok(Expr) containing the symbolic determinant expression, or Err(MathError::InvalidOperation) for non-square or empty matrices.
use mathcore::matrix::SymbolicMatrix;

let m = SymbolicMatrix::from_vec(vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0],
]).unwrap();
let det = m.determinant().unwrap();
println!("det = {}", det); // 1*4 - 2*3  =  -2

trace

Returns the symbolic sum of the main diagonal entries. Requires a square matrix.
pub fn trace(&self) -> Result<Expr, MathError>
Returns Ok(Expr) with the sum data[0][0] + data[1][1] + ..., or Err(MathError::InvalidOperation) for non-square matrices.

Eigenvalues, Characteristic Polynomial, and Decompositions

These operations are provided by LinearAlgebra and operate on numerical nalgebra matrices (DMatrix<f64>) rather than the symbolic SymbolicMatrix type.

pub struct LinearAlgebra

A zero-sized unit struct providing numerical linear algebra routines backed by nalgebra.
pub struct LinearAlgebra;

solve_system

Solves the linear system Ax = b using LU decomposition with partial pivoting (via nalgebra’s lu().solve()).
pub fn solve_system(
    a: &DMatrix<f64>,
    b: &DVector<f64>,
) -> Result<DVector<f64>, MathError>
a
&DMatrix<f64>
required
The coefficient matrix. Must be square and non-singular.
b
&DVector<f64>
required
The right-hand side vector. Its length must equal the number of rows in a.
Returns Ok(DVector<f64>) containing the solution vector x, or Err(MathError::InvalidOperation("System has no unique solution")) when the matrix is singular.
use mathcore::matrix::LinearAlgebra;
use nalgebra::{DMatrix, DVector};

// Solve: 2x + y = 5
//         x + 3y = 10
let a = DMatrix::from_row_slice(2, 2, &[2.0, 1.0, 1.0, 3.0]);
let b = DVector::from_row_slice(&[5.0, 10.0]);
let x = LinearAlgebra::solve_system(&a, &b).unwrap();
println!("x = {:.4}, y = {:.4}", x[0], x[1]);

eigenvalues

Computes all eigenvalues of a square matrix using Schur decomposition. Returns complex eigenvalues in a Vec<Complex64>.
pub fn eigenvalues(matrix: &DMatrix<f64>) -> Result<Vec<Complex64>, MathError>
matrix
&DMatrix<f64>
required
A square numeric matrix.
Returns Ok(Vec<Complex64>) with one entry per eigenvalue, or Err(MathError::InvalidOperation) for non-square input.

qr_decomposition

Decomposes a matrix into an orthogonal matrix Q and an upper-triangular matrix R such that A = QR.
pub fn qr_decomposition(matrix: &DMatrix<f64>) -> (DMatrix<f64>, DMatrix<f64>)
Returns the tuple (Q, R).

svd

Computes the full Singular Value Decomposition A = U Σ Vᵀ.
pub fn svd(matrix: &DMatrix<f64>) -> Result<(DMatrix<f64>, DVector<f64>, DMatrix<f64>), MathError>
Returns Ok((U, singular_values, Vᵀ)) on success, or Err(MathError::InvalidOperation("SVD computation failed")) on failure.
use mathcore::matrix::LinearAlgebra;
use nalgebra::DMatrix;

let a = DMatrix::from_row_slice(3, 2, &[
    1.0, 0.0,
    0.0, 1.0,
    1.0, 1.0,
]);
let (u, sigma, vt) = LinearAlgebra::svd(&a).unwrap();
println!("Singular values: {}", sigma);

rank

Estimates the numerical rank of a matrix by counting the number of singular values that exceed tolerance. Uses SVD internally.
pub fn rank(matrix: &DMatrix<f64>, tolerance: f64) -> usize
matrix
&DMatrix<f64>
required
The matrix whose rank is to be estimated.
tolerance
f64
required
Singular values strictly greater than this threshold are counted as non-zero. A typical value is 1e-10.
Returns The numerical rank as a usize.
use mathcore::matrix::LinearAlgebra;
use nalgebra::DMatrix;

// Full-rank 2×2 matrix
let a = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 1.0]);
assert_eq!(LinearAlgebra::rank(&a, 1e-10), 2);

// Rank-deficient matrix
let b = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 2.0, 4.0]);
assert_eq!(LinearAlgebra::rank(&b, 1e-10), 1);

norm

Computes a matrix norm of the requested type. Four norm types are supported; see NormType below.
pub fn norm(matrix: &DMatrix<f64>, norm_type: NormType) -> f64
matrix
&DMatrix<f64>
required
The matrix to compute the norm of.
norm_type
NormType
required
The norm variant to compute. See NormType for available options.
Returns The computed norm as an f64.
use mathcore::matrix::{LinearAlgebra, NormType};
use nalgebra::DMatrix;

let a = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);

let frob = LinearAlgebra::norm(&a, NormType::Frobenius);
println!("Frobenius norm: {:.4}", frob); // sqrt(1+4+9+16) = sqrt(30)

condition_number

Computes the condition number of a square matrix as the ratio of its largest to smallest singular value. A large condition number indicates a nearly-singular matrix that is sensitive to perturbations.
pub fn condition_number(matrix: &DMatrix<f64>) -> Result<f64, MathError>
matrix
&DMatrix<f64>
required
A square matrix. Non-square input returns an error.
Returns Ok(f64) with the condition number (σ_max / σ_min). Returns Ok(f64::INFINITY) when the smallest singular value is effectively zero (below 1e-15). Returns Err(MathError::InvalidOperation) for non-square input.
use mathcore::matrix::LinearAlgebra;
use nalgebra::DMatrix;

let a = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 2.0]);
let cond = LinearAlgebra::condition_number(&a).unwrap();
println!("Condition number: {:.4}", cond); // 2.0

pub enum NormType

Selects the matrix norm variant used by LinearAlgebra::norm.
#[derive(Debug, Clone, Copy)]
pub enum NormType {
    Frobenius,
    L1,
    L2,
    LInf,
}
VariantDefinition
FrobeniusSquare root of the sum of squared entries: √(Σ aᵢⱼ²)
L1Maximum absolute column sum: `max_j Σᵢaᵢⱼ`
L2Largest singular value (spectral norm): σ_max
LInfMaximum absolute row sum: `max_i Σⱼaᵢⱼ`

Build docs developers (and LLMs) love