Matrix Operations

Work with matrices symbolically and numerically in MathHook, with full support for noncommutative algebra where order matters. Create matrices, perform operations, and solve matrix equations.

📐

Mathematical Definition

Matrix multiplication: For Am×nA_{m \times n} and Bn×pB_{n \times p}:

Cij=k=1nAikBkjC_{ij} = \sum_{k=1}^{n} A_{ik} B_{kj}

Matrix inverse: A×A1=A1×A=IA \times A^{-1} = A^{-1} \times A = I

Determinant (2×2):

det(ab cd)=adbc\det\begin{pmatrix} a & b \ c & d \end{pmatrix} = ad - bc

Code Examples

Creating Matrices

Create matrix symbols and numeric matrices

// Matrix symbols (noncommutative)
let A = symbol!(A; matrix);
let B = symbol!(B; matrix);

// Numeric 2×2 matrix
let M = Expression::matrix(vec![
    vec![expr!(1), expr!(2)],
    vec![expr!(3), expr!(4)],
]);

Matrix Multiplication (Noncommutative)

A*B ≠ B*A in general

let A = symbol!(A; matrix);
let B = symbol!(B; matrix);

let AB = expr!(A * B);  // A*B
let BA = expr!(B * A);  // B*A ≠ A*B

Solving Linear System Ax=b

Solve matrix equation using inverse

let A = Expression::matrix(vec![
    vec![expr!(2), expr!(1)],
    vec![expr!(1), expr!(-1)],
]);
let b = Expression::matrix(vec![
    vec![expr!(5)],
    vec![expr!(1)],
]);

// Solution: x = A^(-1)*b
let x = expr!(A^(-1) * b);
// Result: [[2], [1]]

Matrix Equation A*X=B (Left Division)

Solve for matrix unknown X

let solver = MatrixEquationSolver::new();
let A = symbol!(A; matrix);
let X = symbol!(X; matrix);
let B = symbol!(B; matrix);

let equation = expr!((A * X) - B);
let solution = solver.solve(&equation, &X);
// Returns: X = A^(-1)*B (left division)

🔗 Related Topics