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.

MathCore’s matrix module bridges symbolic computation and high-performance numerical linear algebra. SymbolicMatrix stores matrix entries as symbolic Expr trees, so determinants, traces, and arithmetic return expressions you can further differentiate or simplify — while LinearAlgebra delegates the heavy numerical work (eigenvalues, decompositions, linear solves) to nalgebra, a battle-tested Rust linear algebra library that can leverage BLAS when available.

Imports

use mathcore::matrix::{SymbolicMatrix, LinearAlgebra};
use nalgebra::{DMatrix, DVector};

SymbolicMatrix

SymbolicMatrix is a dynamically sized matrix whose elements are MathCore Expr values. Every entry can be a numeric constant, a symbol, or an arbitrarily complex expression.
#[derive(Debug, Clone)]
pub struct SymbolicMatrix {
    rows: usize,
    cols: usize,
    data: Vec<Vec<Expr>>,
}

Construction

SymbolicMatrix::new(rows, cols)

Creates an all-zero matrix of the given dimensions.
let m = SymbolicMatrix::new(3, 3); // 3×3 zero matrix

SymbolicMatrix::identity(size)

Creates an n × n identity matrix.
let eye = SymbolicMatrix::identity(4); // 4×4 identity

SymbolicMatrix::from_vec(data: Vec<Vec<f64>>) -> Result<SymbolicMatrix, MathError>

Constructs a symbolic matrix from a nested Vec<f64>. Each f64 value is lifted into an Expr::Number. Returns MathError::InvalidOperation if the input is empty or rows have inconsistent lengths.
let matrix = SymbolicMatrix::from_vec(vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0],
]).unwrap();
All rows must have the same length. Ragged input returns Err(MathError::InvalidOperation("Inconsistent row lengths")).

Element Access

get(row, col) -> Option<&Expr>

Returns a reference to the element at (row, col), or None if the index is out of bounds.

set(row, col, value: Expr) -> Result<(), MathError>

Writes a new symbolic value at the given position.
use mathcore::types::Expr;

let mut m = SymbolicMatrix::new(2, 2);
m.set(0, 0, Expr::Number(42.0)).unwrap();

let val = m.get(0, 0).unwrap(); // Expr::Number(42.0)

Arithmetic

add(&other) -> Result<SymbolicMatrix, MathError>

Returns the element-wise sum. Both matrices must have identical dimensions.

multiply(&other) -> Result<SymbolicMatrix, MathError>

Returns the matrix product. The number of columns in self must equal the number of rows in other.
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 product = a.multiply(&b).unwrap();
let sum = a.add(&b).unwrap();
Arithmetic results are symbolic — each entry is an Expr tree representing the formula, not a pre-evaluated number. This lets you compose operations and differentiate the result later.

transpose() -> SymbolicMatrix

Returns the transpose (infallible — no allocation can fail for a swap).

Properties

determinant() -> Result<Expr, MathError>

Computes the determinant symbolically via cofactor expansion. Returns an Expr that you can evaluate or simplify. Requires a square matrix.
  • 1×1: returns the single element directly.
  • 2×2: returns a*d - b*c.
  • n×n: recursive cofactor expansion along the first row.
let matrix = SymbolicMatrix::from_vec(vec![
    vec![1.0, 2.0],
    vec![3.0, 4.0],
]).unwrap();

let det = matrix.determinant().unwrap();
println!("Determinant: {}", det); // 1*4 - 2*3 = -2
Because the result is an Expr, you can call MathCore::simplify on it or substitute symbols if your matrix contained symbolic entries.

trace() -> Result<Expr, MathError>

Returns the sum of diagonal elements as a symbolic expression. Requires a square matrix.

LinearAlgebra

LinearAlgebra is a unit struct (no state) that exposes static methods for numerical computations, all operating on nalgebra’s DMatrix<f64> and DVector<f64> types.

Solving Linear Systems

LinearAlgebra::solve_system(a: &DMatrix<f64>, b: &DVector<f64>) -> Result<DVector<f64>, MathError>

Solves the linear system Ax = b using nalgebra’s LU decomposition. Returns MathError::InvalidOperation if the system has no unique solution (singular or underdetermined matrix).
use mathcore::matrix::LinearAlgebra;
use nalgebra::{DMatrix, DVector};

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

let solution = LinearAlgebra::solve_system(&a, &b).unwrap();
println!("Solution: {:?}", solution); // x=1, y=2

Eigenvalues

LinearAlgebra::eigenvalues(matrix: &DMatrix<f64>) -> Result<Vec<Complex64>, MathError>

Computes complex eigenvalues via the Schur decomposition. Returns MathError::InvalidOperation for non-square matrices.
use mathcore::matrix::LinearAlgebra;
use nalgebra::DMatrix;

let m = DMatrix::from_row_slice(2, 2, &[4.0, 1.0, 2.0, 3.0]);
let eigenvalues = LinearAlgebra::eigenvalues(&m).unwrap();
println!("Eigenvalues: {:?}", eigenvalues);

QR Decomposition

LinearAlgebra::qr_decomposition(matrix: &DMatrix<f64>) -> (DMatrix<f64>, DMatrix<f64>)

Returns the tuple (Q, R) from the QR decomposition. Q is orthogonal and R is upper triangular.
let (q, r) = LinearAlgebra::qr_decomposition(&m);

Singular Value Decomposition (SVD)

LinearAlgebra::svd(matrix: &DMatrix<f64>) -> Result<(DMatrix<f64>, DVector<f64>, DMatrix<f64>), MathError>

Returns (U, singular_values, Vᵀ). Fails only if nalgebra’s SVD backend fails to converge (extremely rare).
let (u, sigma, vt) = LinearAlgebra::svd(&m).unwrap();
println!("Singular values: {:?}", sigma);

Matrix Rank

LinearAlgebra::rank(matrix: &DMatrix<f64>, tolerance: f64) -> usize

Counts the number of singular values above tolerance. A good default tolerance for f64 matrices is 1e-10.

Matrix Norm

LinearAlgebra::norm(matrix: &DMatrix<f64>, norm_type: NormType) -> f64

Supported norm types from the NormType enum:
VariantDescription
NormType::Frobenius√(∑ aᵢⱼ²) — element-wise Euclidean norm
NormType::L1Maximum absolute column sum
NormType::L2Largest singular value (spectral norm)
NormType::LInfMaximum absolute row sum
use mathcore::matrix::{LinearAlgebra, NormType};

let frob = LinearAlgebra::norm(&m, NormType::Frobenius);
let spectral = LinearAlgebra::norm(&m, NormType::L2);

Condition Number

LinearAlgebra::condition_number(matrix: &DMatrix<f64>) -> Result<f64, MathError>

Returns the ratio of the largest to smallest singular value — a measure of numerical stability. Returns f64::INFINITY for singular matrices.
A condition number above ~10⁸ for f64 matrices indicates potential numerical issues in solve operations. Consider using PrecisionNumber for exact arithmetic instead.

Full Example

use mathcore::matrix::{SymbolicMatrix, LinearAlgebra};
use nalgebra::{DMatrix, DVector};

fn main() {
    // Build a 2×2 symbolic matrix and compute its determinant
    let matrix = SymbolicMatrix::from_vec(vec![
        vec![1.0, 2.0],
        vec![3.0, 4.0],
    ]).unwrap();

    let det = matrix.determinant().unwrap();
    println!("Determinant: {}", det); // 1*4 - 2*3

    let trace = matrix.trace().unwrap();
    println!("Trace: {}", trace); // 1 + 4

    let transposed = matrix.transpose();
    println!("{}", transposed);

    // Solve Ax = b numerically
    let a = DMatrix::from_row_slice(2, 2, &[1.0, 2.0, 3.0, 4.0]);
    let b = DVector::from_row_slice(&[5.0, 11.0]);
    let solution = LinearAlgebra::solve_system(&a, &b).unwrap();
    println!("Solution x: {:?}", solution); // [1.0, 2.0]

    // Eigenvalues
    let eigenvalues = LinearAlgebra::eigenvalues(&a).unwrap();
    println!("Eigenvalues: {:?}", eigenvalues);

    // SVD
    let (u, sigma, vt) = LinearAlgebra::svd(&a).unwrap();
    println!("Singular values: {:?}", sigma);
    println!("U:\n{}", u);
    println!("Vᵀ:\n{}", vt);
}

nalgebra Dependency

MathCore’s LinearAlgebra methods operate on nalgebra types directly. Make sure both crates are in your Cargo.toml:
[dependencies]
mathcore = "0.3.1"
nalgebra = "0.32"
nalgebra optionally links against OpenBLAS or other BLAS/LAPACK backends for faster matrix operations on large matrices. See the nalgebra docs for details.

Build docs developers (and LLMs) love