sokobo
Loading...
Searching...
No Matches
Matrix< T > Class Template Reference

A templated matrix class supporting various linear algebra operations. More...

#include <matrix.h>

Public Member Functions

 Matrix ()
 Default constructor creating an empty 0×0 matrix.
 
 Matrix (int r, int c)
 Constructs a matrix with specified dimensions, initialized with default values.
 
 Matrix (const std::vector< std::vector< T > > &mat)
 Constructs a matrix from a 2D vector.
 
T & operator() (int row, int column)
 Accesses matrix element at specified position (non-const).
 
const T & operator() (int row, int column) const
 Accesses matrix element at specified position (const).
 
std::vector< T > & operator[] (int i)
 Accesses a row of the matrix (non-const).
 
const std::vector< T > & operator[] (int i) const
 Accesses a row of the matrix (const).
 
Matrix< T > operator+ (const Matrix< T > &other) const
 Matrix addition.
 
Matrix< T > operator- (const Matrix< T > &other) const
 Matrix subtraction.
 
Matrix< T > operator* (const Matrix< T > &other) const
 Matrix multiplication.
 
Matrix< T > operator* (const T &scalar) const
 Scalar multiplication.
 
Matrix< T > operator/= (const Matrix< T > &other) const
 Element-wise division.
 
Matrix< T > operator-= (const Matrix< T > &other) const
 In-place subtraction.
 
determinant () const
 Computes the determinant of the matrix.
 
Matrix< T > inverse () const
 Computes the inverse of the matrix.
 
Matrix< T > transpose () const
 Computes the transpose of the matrix.
 
std::vector< T > eigenvalues () const
 Computes the eigenvalues of the matrix.
 
Matrix< T > eigenvectors () const
 Computes the eigenvectors of the matrix.
 
Matrix< T > adjoint () const
 Computes the adjoint (adjugate) matrix.
 
Matrix< T > submatrix (int row_start, int row_end, int col_start, int col_end) const
 Extracts a submatrix from specified row and column ranges.
 
rank () const
 Computes the rank of the matrix.
 
bool isSymmetric () const
 Checks if the matrix is symmetric.
 
std::pair< Matrix< T >, Matrix< T > > LUDecomposition () const
 Performs LU decomposition of the matrix.
 
std::pair< Matrix< T >, Matrix< T > > QRDecomposition () const
 Performs QR decomposition of the matrix using Gram-Schmidt orthogonalization.
 
std::vector< T > matVec (const std::vector< T > &v) const
 Performs matrix-vector multiplication.
 
dot (const std::vector< T > &a, const std::vector< T > &b) const
 Computes the dot product of two vectors.
 
void normalize (std::vector< T > &v) const
 Normalizes a vector to unit length (in-place).
 
void lanczos (int m, std::vector< T > &alpha, std::vector< T > &beta, Matrix< T > &Q) const
 Performs the Lanczos algorithm for tridiagonalization.
 
Matrix< T > buildTridiagonal (const std::vector< T > &alpha, const std::vector< T > &beta, int m) const
 Constructs a tridiagonal matrix from diagonal and off-diagonal elements.
 
double frobeniusNorm () const
 Computes the Frobenius norm of the matrix.
 
double spectralNorm () const
 Computes the spectral norm (2-norm) of the matrix.
 
double norm (const std::vector< T > &v) const
 Computes the Euclidean (L2) norm of a vector.
 
Matrix< T > getMinor (int row, int col) const
 Gets the minor matrix by removing a specified row and column.
 
std::string toString () const
 Converts the matrix to a formatted string representation.
 
int getRows () const
 Gets the number of rows in the matrix.
 
int getCols () const
 Gets the number of columns in the matrix.
 

Static Public Member Functions

static Matrix< T > identity (int n)
 Creates an n × n identity matrix.
 
static Matrix< T > zeros (int r, int c)
 Creates an r × c matrix filled with zeros.
 
static Matrix< T > ones (int r, int c)
 Creates an r × c matrix filled with ones.
 

Friends

std::ostream & operator<< (std::ostream &os, const Matrix< T > &m)
 Stream output operator for formatted matrix display.
 

Detailed Description

template<typename T>
class Matrix< T >

A templated matrix class supporting various linear algebra operations.

This class provides a comprehensive implementation of matrix operations including basic arithmetic, advanced operations (determinant, inverse, eigenvalues), matrix decompositions (LU, QR), and iterative algorithms (Lanczos). Supports both real arithmetic types and complex number types.

Template Parameters
TThe element type. Can be arithmetic types (int, float, double) or complex number types (ComplexNumber).

Definition at line 22 of file matrix.h.

Constructor & Destructor Documentation

◆ Matrix() [1/3]

template<typename T >
Matrix< T >::Matrix ( )
inline

Default constructor creating an empty 0×0 matrix.

Definition at line 34 of file matrix.h.

◆ Matrix() [2/3]

template<typename T >
Matrix< T >::Matrix ( int  r,
int  c 
)
inline

Constructs a matrix with specified dimensions, initialized with default values.

Parameters
rNumber of rows
cNumber of columns

Definition at line 46 of file matrix.h.

◆ Matrix() [3/3]

template<typename T >
Matrix< T >::Matrix ( const std::vector< std::vector< T > > &  mat)

Constructs a matrix from a 2D vector.

Parameters
matA 2D vector containing the matrix data
Exceptions
std::invalid_argumentif rows have inconsistent lengths

Definition at line 113 of file matrix.cpp.

Member Function Documentation

◆ adjoint()

template<typename T >
Matrix< T > Matrix< T >::adjoint

Computes the adjoint (adjugate) matrix.

The adjoint is the transpose of the cofactor matrix.

Returns
Adjoint matrix
Exceptions
std::invalid_argumentif matrix is not square

Definition at line 403 of file matrix.cpp.

◆ buildTridiagonal()

template<typename T >
Matrix< T > Matrix< T >::buildTridiagonal ( const std::vector< T > &  alpha,
const std::vector< T > &  beta,
int  m 
) const

Constructs a tridiagonal matrix from diagonal and off-diagonal elements.

Parameters
alphaDiagonal elements
betaOff-diagonal elements
mDimension of the tridiagonal matrix
Returns
m × m tridiagonal matrix

Definition at line 847 of file matrix.cpp.

◆ determinant()

template<typename T >
T Matrix< T >::determinant

Computes the determinant of the matrix.

The calculation follows these rules based on the matrix dimension \( n \times n \):

  • For \( n = 1 \):

    \[ \det(A) = a_{1,1} \]

  • For \( n = 2 \):

    \[ \det(A) = a_{0,0}a_{1,1} - a_{0,1}a_{1,0} \]

  • For \( n > 2 \), using LU Decomposition \( A = LU \):

    \[ \det(A) = \det(L)\det(U) = \prod_{i=0}^{n-1} u_{i,i} \]

    *(Note: \( \det(L) = 1 \) as it is a unit triangular matrix)*.
Returns
Determinant value of type \( T \).
Exceptions
std::invalid_argumentIf the matrix is not square ( \( rows \neq cols \)).

Definition at line 276 of file matrix.cpp.

◆ dot()

template<typename T >
T Matrix< T >::dot ( const std::vector< T > &  a,
const std::vector< T > &  b 
) const

Computes the dot product of two vectors.

Parameters
aFirst vector
bSecond vector
Returns
Dot product value
Exceptions
std::invalid_argumentif vectors have different sizes

Definition at line 733 of file matrix.cpp.

◆ eigenvalues()

template<typename T >
std::vector< T > Matrix< T >::eigenvalues

Computes the eigenvalues of the matrix.

Returns
Vector containing eigenvalues
Exceptions
std::invalid_argumentif matrix is not square

Definition at line 427 of file matrix.cpp.

◆ eigenvectors()

template<typename T >
Matrix< T > Matrix< T >::eigenvectors

Computes the eigenvectors of the matrix.

Returns
Matrix where each column is an eigenvector
Exceptions
std::invalid_argumentif matrix is not square

Definition at line 865 of file matrix.cpp.

◆ frobeniusNorm()

template<typename T >
double Matrix< T >::frobeniusNorm

Computes the Frobenius norm of the matrix.

The Frobenius norm is the square root of the sum of squares of all elements.

Returns
Frobenius norm value

Definition at line 619 of file matrix.cpp.

◆ getCols()

template<typename T >
int Matrix< T >::getCols ( ) const
inline

Gets the number of columns in the matrix.

Returns
Number of columns

Definition at line 425 of file matrix.h.

◆ getMinor()

template<typename T >
Matrix< T > Matrix< T >::getMinor ( int  row,
int  col 
) const

Gets the minor matrix by removing a specified row and column.

Used in computing determinants and adjoints via cofactor expansion.

Parameters
rowRow to remove (0-based)
colColumn to remove (0-based)
Returns
(rows-1) × (cols-1) minor matrix
Exceptions
std::out_of_rangeif row or column index is out of bounds

Definition at line 655 of file matrix.cpp.

◆ getRows()

template<typename T >
int Matrix< T >::getRows ( ) const
inline

Gets the number of rows in the matrix.

Returns
Number of rows

Definition at line 418 of file matrix.h.

◆ identity()

template<typename T >
Matrix< T > Matrix< T >::identity ( int  n)
static

Creates an n × n identity matrix.

The identity matrix has ones on the main diagonal and zeros elsewhere.

Parameters
nDimension of the identity matrix
Returns
n × n identity matrix

Definition at line 706 of file matrix.cpp.

◆ inverse()

template<typename T >
Matrix< T > Matrix< T >::inverse

Computes the inverse of the matrix.

Returns
Inverse matrix
Exceptions
std::invalid_argumentif matrix is not square
std::runtime_errorif matrix is singular (determinant is zero)

Definition at line 303 of file matrix.cpp.

◆ isSymmetric()

template<typename T >
bool Matrix< T >::isSymmetric

Checks if the matrix is symmetric.

A matrix is symmetric if A = A^T.

Returns
true if matrix is symmetric, false otherwise
Exceptions
std::invalid_argumentif matrix is not square

Definition at line 258 of file matrix.cpp.

◆ lanczos()

template<typename T >
void Matrix< T >::lanczos ( int  m,
std::vector< T > &  alpha,
std::vector< T > &  beta,
Matrix< T > &  Q 
) const

Performs the Lanczos algorithm for tridiagonalization.

The Lanczos algorithm is an iterative method for computing eigenvalues and eigenvectors of large sparse symmetric matrices. It reduces the matrix to tridiagonal form.

Parameters
mNumber of Lanczos iterations
alphaOutput vector of diagonal elements (size m)
betaOutput vector of off-diagonal elements (size m-1)
QOutput matrix of orthonormal Lanczos vectors (n × m)
Exceptions
std::invalid_argumentif matrix is not square or m > matrix size

Definition at line 792 of file matrix.cpp.

◆ LUDecomposition()

template<typename T >
std::pair< Matrix< T >, Matrix< T > > Matrix< T >::LUDecomposition

Performs LU decomposition of the matrix.

Decomposes the matrix into lower triangular (L) and upper triangular (U) matrices such that A = LU.

Returns
Pair of matrices (L, U)
Exceptions
std::invalid_argumentif matrix is not square
std::runtime_errorif decomposition fails (singular matrix)

Definition at line 533 of file matrix.cpp.

◆ matVec()

template<typename T >
std::vector< T > Matrix< T >::matVec ( const std::vector< T > &  v) const

Performs matrix-vector multiplication.

Parameters
vVector to multiply with
Returns
Resulting vector after multiplication
Exceptions
std::invalid_argumentif vector size doesn't match matrix columns

Definition at line 721 of file matrix.cpp.

◆ norm()

template<typename T >
double Matrix< T >::norm ( const std::vector< T > &  v) const

Computes the Euclidean (L2) norm of a vector.

Parameters
vVector to compute norm for
Returns
L2 norm value

Definition at line 743 of file matrix.cpp.

◆ normalize()

template<typename T >
void Matrix< T >::normalize ( std::vector< T > &  v) const

Normalizes a vector to unit length (in-place).

Parameters
vVector to normalize
Exceptions
std::runtime_errorif vector has zero norm

Definition at line 749 of file matrix.cpp.

◆ ones()

template<typename T >
Matrix< T > Matrix< T >::ones ( int  r,
int  c 
)
static

Creates an r × c matrix filled with ones.

Parameters
rNumber of rows
cNumber of columns
Returns
r × c matrix of ones

Definition at line 909 of file matrix.cpp.

◆ operator()() [1/2]

template<typename T >
T & Matrix< T >::operator() ( int  row,
int  column 
)

Accesses matrix element at specified position (non-const).

Parameters
rowRow index (0-based)
columnColumn index (0-based)
Returns
Reference to the element at (row, column)

Definition at line 134 of file matrix.cpp.

◆ operator()() [2/2]

template<typename T >
const T & Matrix< T >::operator() ( int  row,
int  column 
) const

Accesses matrix element at specified position (const).

Parameters
rowRow index (0-based)
columnColumn index (0-based)
Returns
Const reference to the element at (row, column)

Definition at line 146 of file matrix.cpp.

◆ operator*() [1/2]

template<typename T >
Matrix< T > Matrix< T >::operator* ( const Matrix< T > &  other) const

Matrix multiplication.

Parameters
otherMatrix to multiply with
Returns
Result of matrix multiplication
Exceptions
std::invalid_argumentif dimensions are incompatible (this.cols != other.rows)

Definition at line 190 of file matrix.cpp.

◆ operator*() [2/2]

template<typename T >
Matrix< T > Matrix< T >::operator* ( const T &  scalar) const

Scalar multiplication.

Parameters
scalarScalar value to multiply all elements by
Returns
Result of scalar multiplication

Definition at line 211 of file matrix.cpp.

◆ operator+()

template<typename T >
Matrix< T > Matrix< T >::operator+ ( const Matrix< T > &  other) const

Matrix addition.

Parameters
otherMatrix to add
Returns
Result of element-wise addition
Exceptions
std::invalid_argumentif matrices have different dimensions

Definition at line 158 of file matrix.cpp.

◆ operator-()

template<typename T >
Matrix< T > Matrix< T >::operator- ( const Matrix< T > &  other) const

Matrix subtraction.

Parameters
otherMatrix to subtract
Returns
Result of element-wise subtraction
Exceptions
std::invalid_argumentif matrices have different dimensions

Definition at line 174 of file matrix.cpp.

◆ operator-=()

template<typename T >
Matrix< T > Matrix< T >::operator-= ( const Matrix< T > &  other) const

In-place subtraction.

Parameters
otherMatrix to subtract
Returns
Result of element-wise subtraction
Exceptions
std::invalid_argumentif matrices have different dimensions

◆ operator/=()

template<typename T >
Matrix< T > Matrix< T >::operator/= ( const Matrix< T > &  other) const

Element-wise division.

Parameters
otherMatrix to divide by
Returns
Result of element-wise division
Exceptions
std::invalid_argumentif matrices have different dimensions
std::runtime_errorif division by zero occurs

◆ operator[]() [1/2]

template<typename T >
std::vector< T > & Matrix< T >::operator[] ( int  i)
inline

Accesses a row of the matrix (non-const).

Parameters
iRow index (0-based)
Returns
Reference to the row vector

Definition at line 85 of file matrix.h.

◆ operator[]() [2/2]

template<typename T >
const std::vector< T > & Matrix< T >::operator[] ( int  i) const
inline

Accesses a row of the matrix (const).

Parameters
iRow index (0-based)
Returns
Const reference to the row vector

Definition at line 93 of file matrix.h.

◆ QRDecomposition()

template<typename T >
std::pair< Matrix< T >, Matrix< T > > Matrix< T >::QRDecomposition

Performs QR decomposition of the matrix using Gram-Schmidt orthogonalization.

Decomposes the matrix into an orthogonal matrix (Q) and an upper triangular matrix (R) such that A = QR.

Returns
Pair of matrices (Q, R)
Exceptions
std::invalid_argumentif matrix has more columns than rows

Definition at line 563 of file matrix.cpp.

◆ rank()

template<typename T >
T Matrix< T >::rank

Computes the rank of the matrix.

The rank is the number of linearly independent rows or columns.

Returns
Rank of the matrix

Definition at line 223 of file matrix.cpp.

◆ spectralNorm()

template<typename T >
double Matrix< T >::spectralNorm

Computes the spectral norm (2-norm) of the matrix.

The spectral norm is the largest singular value, equal to the square root of the largest eigenvalue of A^T * A.

Returns
Spectral norm value

Definition at line 633 of file matrix.cpp.

◆ submatrix()

template<typename T >
Matrix< T > Matrix< T >::submatrix ( int  row_start,
int  row_end,
int  col_start,
int  col_end 
) const

Extracts a submatrix from specified row and column ranges.

Extracts rows [row_start, row_end) and columns [col_start, col_end) using exclusive upper bounds.

Parameters
row_startStarting row index (inclusive)
row_endEnding row index (exclusive)
col_startStarting column index (inclusive)
col_endEnding column index (exclusive)
Returns
Extracted submatrix
Exceptions
std::out_of_rangeif indices are out of bounds

Definition at line 763 of file matrix.cpp.

◆ toString()

template<typename T >
std::string Matrix< T >::toString

Converts the matrix to a formatted string representation.

Returns
String representation of the matrix

Definition at line 684 of file matrix.cpp.

◆ transpose()

template<typename T >
Matrix< T > Matrix< T >::transpose

Computes the transpose of the matrix.

Returns
Transposed matrix with dimensions swapped

Definition at line 391 of file matrix.cpp.

◆ zeros()

template<typename T >
Matrix< T > Matrix< T >::zeros ( int  r,
int  c 
)
static

Creates an r × c matrix filled with zeros.

Parameters
rNumber of rows
cNumber of columns
Returns
r × c zero matrix

Definition at line 899 of file matrix.cpp.

Friends And Related Function Documentation

◆ operator<<

template<typename T >
std::ostream & operator<< ( std::ostream &  os,
const Matrix< T > &  m 
)
friend

Stream output operator for formatted matrix display.

Outputs the matrix with fixed-point notation, 6 decimal places, and field width of 12.

Parameters
osOutput stream
mMatrix to output
Returns
Reference to the output stream

Definition at line 162 of file matrix.h.


The documentation for this class was generated from the following files: