Skip to main content

Matrix

Struct Matrix 

Source
pub struct Matrix { /* private fields */ }
Expand description

A dense matrix stored in row-major order.

§Storage

Elements are stored contiguously: data[i * cols + j] holds A[i, j].

Implementations§

Source§

impl Matrix

Source

pub fn new( rows: usize, cols: usize, data: Vec<f64>, ) -> Result<Self, MatrixError>

Creates a matrix from raw data in row-major order.

§Errors

Returns Err if data.len() != rows * cols.

§Examples
use u_numflow::matrix::Matrix;
let m = Matrix::new(2, 3, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
assert_eq!(m.get(0, 2), 3.0);
assert_eq!(m.get(1, 0), 4.0);
Source

pub fn from_rows(rows: &[&[f64]]) -> Self

Creates a matrix from row slices.

§Panics

Panics if rows have inconsistent lengths or rows is empty.

§Examples
use u_numflow::matrix::Matrix;
let m = Matrix::from_rows(&[&[1.0, 2.0], &[3.0, 4.0]]);
assert_eq!(m.get(1, 1), 4.0);
Source

pub fn zeros(rows: usize, cols: usize) -> Self

Creates a zero matrix.

Source

pub fn identity(n: usize) -> Self

Creates an identity matrix.

§Examples
use u_numflow::matrix::Matrix;
let eye = Matrix::identity(3);
assert_eq!(eye.get(0, 0), 1.0);
assert_eq!(eye.get(0, 1), 0.0);
assert_eq!(eye.get(2, 2), 1.0);
Source

pub fn from_col(data: &[f64]) -> Self

Creates a column vector (n×1 matrix) from a slice.

Source

pub fn rows(&self) -> usize

Number of rows.

Source

pub fn cols(&self) -> usize

Number of columns.

Source

pub fn get(&self, row: usize, col: usize) -> f64

Returns the element at (row, col).

§Panics

Panics if indices are out of bounds.

Source

pub fn set(&mut self, row: usize, col: usize, value: f64)

Sets the element at (row, col).

§Panics

Panics if indices are out of bounds.

Source

pub fn data(&self) -> &[f64]

Returns the raw data as a slice.

Source

pub fn row(&self, row: usize) -> &[f64]

Returns a row as a slice.

Source

pub fn diag(&self) -> Vec<f64>

Returns the diagonal elements.

Source

pub fn is_square(&self) -> bool

Returns true if the matrix is square.

Source

pub fn transpose(&self) -> Self

Transpose: returns Aᵀ.

§Examples
use u_numflow::matrix::Matrix;
let m = Matrix::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0]]);
let t = m.transpose();
assert_eq!(t.rows(), 3);
assert_eq!(t.cols(), 2);
assert_eq!(t.get(0, 1), 4.0);
Source

pub fn add(&self, other: &Self) -> Result<Self, MatrixError>

Matrix addition: A + B.

§Errors

Returns Err if dimensions do not match.

Source

pub fn sub(&self, other: &Self) -> Result<Self, MatrixError>

Matrix subtraction: A - B.

§Errors

Returns Err if dimensions do not match.

Source

pub fn scale(&self, c: f64) -> Self

Scalar multiplication: c · A.

Source

pub fn mul_mat(&self, other: &Self) -> Result<Self, MatrixError>

Matrix multiplication: A · B.

Uses i-k-j loop order for better cache locality on row-major storage.

§Errors

Returns Err if self.cols != other.rows.

§Complexity

O(n·m·p) where self is n×m and other is m×p.

§Examples
use u_numflow::matrix::Matrix;
let a = Matrix::identity(3);
let b = Matrix::from_rows(&[&[1.0, 2.0, 3.0], &[4.0, 5.0, 6.0], &[7.0, 8.0, 9.0]]);
let c = a.mul_mat(&b).unwrap();
assert_eq!(c.get(2, 2), 9.0);
Source

pub fn mul_vec(&self, v: &[f64]) -> Result<Vec<f64>, MatrixError>

Matrix-vector multiplication: A · v.

§Errors

Returns Err if self.cols != v.len().

Source

pub fn frobenius_norm(&self) -> f64

Frobenius norm: ‖A‖_F = √(Σᵢⱼ aᵢⱼ²).

Source

pub fn is_symmetric(&self, tol: f64) -> bool

Checks whether the matrix is symmetric within tolerance.

Source

pub fn determinant(&self) -> Result<f64, MatrixError>

Determinant via LU decomposition with partial pivoting.

§Errors

Returns Err(NotSquare) if the matrix is not square. Returns Err(Singular) if a zero pivot is encountered.

§Complexity

O(n³/3).

§Examples
use u_numflow::matrix::Matrix;
let m = Matrix::from_rows(&[&[2.0, 3.0], &[1.0, 4.0]]);
assert!((m.determinant().unwrap() - 5.0).abs() < 1e-10);
Source

pub fn inverse(&self) -> Result<Self, MatrixError>

Matrix inverse via Gauss-Jordan elimination with partial pivoting.

§Algorithm

Augments [A | I], reduces to [I | A⁻¹] using row operations.

Reference: Golub & Van Loan (1996), Matrix Computations, §1.2.

§Errors

Returns Err(Singular) if the matrix is singular.

§Examples
use u_numflow::matrix::Matrix;
let a = Matrix::from_rows(&[&[4.0, 7.0], &[2.0, 6.0]]);
let inv = a.inverse().unwrap();
let eye = a.mul_mat(&inv).unwrap();
assert!((eye.get(0, 0) - 1.0).abs() < 1e-10);
assert!(eye.get(0, 1).abs() < 1e-10);
Source

pub fn cholesky(&self) -> Result<Self, MatrixError>

Cholesky decomposition: returns lower-triangular L such that A = L·Lᵀ.

§Algorithm

Column-by-column Cholesky-Banachiewicz factorization.

Reference: Golub & Van Loan (1996), Matrix Computations, Algorithm 4.2.1.

§Requirements

Matrix must be symmetric and positive-definite.

§Complexity

O(n³/3).

§Examples
use u_numflow::matrix::Matrix;
let a = Matrix::from_rows(&[
    &[4.0, 2.0],
    &[2.0, 3.0],
]);
let l = a.cholesky().unwrap();
let llt = l.mul_mat(&l.transpose()).unwrap();
assert!((llt.get(0, 0) - 4.0).abs() < 1e-10);
assert!((llt.get(0, 1) - 2.0).abs() < 1e-10);
Source

pub fn cholesky_solve(&self, b: &[f64]) -> Result<Vec<f64>, MatrixError>

Solves the linear system A·x = b using Cholesky decomposition.

Equivalent to computing x = A⁻¹·b but more efficient and stable.

§Algorithm
  1. Decompose A = L·Lᵀ via Cholesky
  2. Solve L·y = b (forward substitution)
  3. Solve Lᵀ·x = y (backward substitution)
§Requirements

Matrix must be symmetric positive-definite. b.len() must equal self.rows().

Source

pub fn eigen_symmetric(&self) -> Result<(Vec<f64>, Matrix), MatrixError>

Eigenvalue decomposition of a real symmetric matrix using the classical Jacobi rotation algorithm.

Returns (eigenvalues, eigenvectors) where eigenvalues are sorted in descending order and eigenvectors are the corresponding columns of the returned matrix (column i is the eigenvector for eigenvalue i).

§Algorithm

Cyclic Jacobi rotations zero off-diagonal elements iteratively. Converges quadratically for symmetric matrices.

Reference: Golub & Van Loan (1996), “Matrix Computations”, §8.4

§Complexity

O(n³) per sweep, typically 5–10 sweeps. Best for n < 200.

§Errors

Returns NotSquare if the matrix is not square, or NotSymmetric if the matrix is not symmetric within tolerance.

§Examples
use u_numflow::matrix::Matrix;

let a = Matrix::from_rows(&[
    &[4.0, 1.0],
    &[1.0, 3.0],
]);
let (eigenvalues, eigenvectors) = a.eigen_symmetric().unwrap();

// Eigenvalues of [[4,1],[1,3]] are (7+√5)/2 ≈ 4.618 and (7-√5)/2 ≈ 2.382
assert!((eigenvalues[0] - 4.618).abs() < 0.01);
assert!((eigenvalues[1] - 2.382).abs() < 0.01);

// Eigenvectors are orthonormal
let dot: f64 = (0..2).map(|i| eigenvectors.get(i, 0) * eigenvectors.get(i, 1)).sum();
assert!(dot.abs() < 1e-10);

Trait Implementations§

Source§

impl Clone for Matrix

Source§

fn clone(&self) -> Matrix

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Matrix

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Matrix

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Matrix

Source§

fn eq(&self, other: &Matrix) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for Matrix

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V