feat(matrix_op): add multiplication

matrix_ops: add matrix multiply capability
chore(fmt): flatten crate directory
tests(ops): add tests for multiplication
This commit is contained in:
Zhongheng Liu 2025-01-23 19:06:49 +02:00
commit 333c6c7281
Signed by: steven
GPG key ID: 805A28B071DAD84B
7 changed files with 70 additions and 40 deletions

18
src/error.rs Normal file
View file

@ -0,0 +1,18 @@
use std::{error::Error, fmt::Display};
#[derive(Debug, PartialEq, Eq)]
pub struct ParseMatrixError;
impl Display for ParseMatrixError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Matrix parsing error")
}
}
impl Error for ParseMatrixError {}
#[derive(Debug)]
pub struct MatrixSetValueError;
impl Error for MatrixSetValueError {}
impl Display for MatrixSetValueError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Matrix set value error")
}
}

View file

@ -9,20 +9,23 @@
//! //!
//! Examples: //! Examples:
//! ``` //! ```
//! ...
//! use matrix::Matrix; //! use matrix::Matrix;
//! let m = Matrix::from_str("1,2,3\n4,5,6\n7,8,9"); //! use std::str::FromStr;
//! let m = Matrix::from_str("1,2,3\n4,5,6\n7,8,9").expect("Expected this to work");
//! println!("Matrix string formatting:\n{}", m); //! println!("Matrix string formatting:\n{}", m);
//! println!("Evaluate determinant of matrix: {}", m.determinant()); //! println!("Evaluate determinant of matrix: {}", m.determinant());
//! println!("Transpose of matrix m:\n{}", m.transpose()); //! println!("Transpose of matrix m:\n{}", m.transpose());
//! ... //!
//! ``` //! ```
pub mod types; mod matrix;
pub mod error;
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
pub use matrix::Matrix;
pub fn test() { pub fn test() {
println!("Testing code here"); println!("Testing code here");
} }

219
src/matrix.rs Normal file
View file

@ -0,0 +1,219 @@
//! Matrix struct and relevant implementations.
//!
//! Example usage - addition of two matrices:
//! ```
//! use matrix::Matrix;
//! use std::str::FromStr;
//! let m1 = Matrix::from_str("1,2\n3,4").expect("Expect parse correct");
//! let m2 = Matrix::from_str("1,1\n1,1").expect("Expect parse correct");
//! let m_add = &m1 + &m2;
//! println!("m1 + m2 =\n{}", m_add);
//! ```
//! TODO:: Create matrix multiplication method
use std::{fmt::Display, ops::{Add, Mul, Sub}, str::FromStr};
use crate::error::{MatrixSetValueError, ParseMatrixError};
#[derive(Debug, PartialEq, Eq)]
pub struct Matrix {
/// Number of rows in matrix.
pub nrows: usize,
/// Number of columns in matrix.
pub ncols: usize,
/// Data stored in the matrix, you should not access this directly
data: Vec<Vec<i32>>,
}
impl FromStr for Matrix {
type Err = ParseMatrixError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut d: Vec<Vec<i32>> = Vec::new();
let rows_iter = s.split('\n');
for txt in rows_iter {
let mut r: Vec<i32> = Vec::new();
for ch in txt.split(',') {
let parsed = match i32::from_str(ch) {
Ok(n) => Ok(n),
Err(_e) => Err(ParseMatrixError),
};
r.push(parsed?);
}
d.push(r);
}
Ok(Matrix::new(d))
}
}
impl Display for Matrix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut builder = String::new();
for (i, r) in self.data.iter().enumerate() {
let mut row_str = if i == 0 || i == self.nrows - 1 {
"+".to_string()
} else {
"|".to_string()
};
for (j, n) in r.iter().enumerate() {
row_str += &format!("{}{}", n, if j == self.ncols - 1 { "" } else { "," });
}
row_str += if i == 0 || i == self.nrows - 1 {
"+\n"
} else {
"|\n"
};
builder += &row_str;
}
write!(f, "{}", builder)
}
}
impl<'a, 'b> Add<&'b Matrix> for &'a Matrix {
type Output = Matrix;
fn add(self, rhs: &'b Matrix) -> Self::Output {
if (self.nrows != rhs.nrows) || (self.ncols != rhs.ncols) {
panic!("Cannot add two matrices with different dimensions");
}
let mut x = Matrix {
nrows: self.nrows,
ncols: self.ncols,
data: self.data.clone(),
};
for (i, r) in rhs.data.iter().enumerate() {
for (j, n) in r.iter().enumerate() {
x.data[i][j] += n;
}
}
x
}
}
impl<'a, 'b> Sub<&'b Matrix> for &'a Matrix {
type Output = Matrix;
fn sub(self, rhs: &'b Matrix) -> Self::Output {
todo!()
}
}
impl<'a, 'b> Mul<&'b Matrix> for &'a Matrix {
type Output = Matrix;
fn mul(self, rhs: &'b Matrix) -> Self::Output {
fn reduce(lhs: &Matrix, rhs: &Matrix, at_r: usize, at_c: usize) -> i32 {
let mut tmp = 0;
for i in 0..lhs.ncols {
tmp += lhs.get(at_r, i).unwrap() * rhs.get(i, at_c).unwrap();
}
tmp
}
let mut d: Vec<Vec<i32>> = Vec::new();
if self.ncols != rhs.nrows {
println!("LHS: \n{}RHS: \n{}", self, rhs);
println!("LHS nrows: {} ;; RHS ncols: {}", self.nrows, rhs.ncols);
panic!()
}
for i in 0..self.nrows {
let mut r: Vec<i32> = Vec::new();
for j in 0..rhs.ncols {
r.push(reduce(self, rhs, i, j));
}
d.push(r);
}
Matrix::new(d)
}
}
impl Matrix {
/// Matrix initialiser function.
///
/// Accepts a new array of data as a list of rows.
///
/// TODOs
/// - Add row length check
pub fn new(data: Vec<Vec<i32>>) -> Matrix {
Matrix {
nrows: data.len(),
ncols: data[0].len(),
data,
}
}
/// Query one element at selected position.
///
/// Returns `None` if index is out of bounds.
pub fn get(&self, row_index: usize, column_index: usize) -> Option<i32> {
let r = self.data.get(row_index)?;
let n = r.get(column_index)?;
Some(*n)
}
/// Update one element at selected position.
///
/// Returns `Err()` if index is out of bounds.
pub fn set(
&mut self,
row_index: usize,
column_index: usize,
new_data: i32,
) -> Result<(), MatrixSetValueError> {
self.data[row_index][column_index] = new_data;
Ok(())
}
/// Checks if this is a square matrix.
pub fn is_square(&self) -> bool {
self.nrows == self.ncols
}
fn splice(&self, at_index: usize) -> Matrix {
let mut data: Vec<Vec<i32>> = Vec::new();
for i in 0..self.data.len() {
if i == 0 {
continue;
}
let mut r: Vec<i32> = Vec::new();
for j in 0..self.data[i].len() {
if j == at_index {
continue;
}
r.push(self.data[i][j]);
}
data.push(r);
}
Matrix::new(data)
}
/// Evaluates any N-by-N matrix.
///
/// This function panics if the matrix is not square!
pub fn determinant(&self) -> i32 {
if !self.is_square() {
panic!()
};
if self.nrows == 2 && self.ncols == 2 {
return self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0];
}
let mut tmp = 0;
for (i, n) in self.data[0].iter().enumerate() {
let mult = if i % 2 == 0 { -*n } else { *n };
let eval = self.splice(i).determinant();
tmp += mult * eval;
}
tmp
}
/// Evaluates the tranpose of the matrix.
///
/// Each row becomes a column, each column becomes a row.
pub fn transpose(&self) -> Matrix {
let mut new_data = Vec::<Vec<i32>>::new();
for i in 0..self.nrows {
let mut new_row = Vec::<i32>::new();
for j in 0..self.ncols {
new_row.push(self.data[j][i]);
}
new_data.push(new_row);
}
Matrix {
nrows: self.ncols,
ncols: self.nrows,
data: new_data,
}
}
}

View file

@ -1,2 +1,3 @@
#[cfg(test)] #[cfg(test)]
pub mod matrix_test; mod matrix_test_parse;
mod matrix_test_ops;

View file

@ -0,0 +1,45 @@
use std::str::FromStr;
use crate::{matrix::Matrix, error::ParseMatrixError};
#[test]
pub fn test_matrix_add() -> Result<(), ParseMatrixError> {
let m1 = Matrix::from_str("1,2,3\n4,5,6\n7,8,9")?;
let m2 = Matrix::from_str("1,1,1\n1,1,1\n1,1,1")?;
let t = Matrix::from_str("2,3,4\n5,6,7\n8,9,10")?;
assert_eq!(&m1 + &m2, t);
Ok(())
}
#[test]
pub fn test_matrix_determinate() -> Result<(), ParseMatrixError> {
let m = Matrix::from_str("3,4\n5,6")?;
let det = 3 * 6 - 4 * 5;
assert_eq!(m.determinant(), det);
Ok(())
}
#[test]
pub fn test_matrix_transposition() -> Result<(), ParseMatrixError> {
let m = Matrix::from_str("1,2,3\n4,5,6\n7,8,9")?;
let t = Matrix::from_str("1,4,7\n2,5,8\n3,6,9")?;
assert_eq!(m.transpose(), t);
Ok(())
}
#[test]
pub fn test_matrix_mul() -> Result<(), ParseMatrixError> {
let m1 = Matrix::from_str("1,2\n1,2")?;
let m2 = Matrix::from_str("1,3\n2,4")?;
let m3 = Matrix::from_str("1,2\n3,4")?;
let m4 = Matrix::from_str("1\n2")?;
let t1 = Matrix::from_str("5,11\n5,11")?;
let t2 = Matrix::from_str("5\n11")?;
assert_eq!(&m1 * &m2, t1);
assert_eq!(&m3 * &m4, t2);
Ok(())
}
#[test]
#[should_panic]
pub fn test_matrix_add_bad_dimensions() -> () {
let bad = Matrix::from_str("1,1,1\n1,1,1").unwrap();
let add = Matrix::from_str("1,1\n1,1").unwrap();
let _ = &bad + &add;
}

View file

@ -0,0 +1,22 @@
use std::str::FromStr;
use crate::{matrix::Matrix, error::ParseMatrixError};
#[test]
pub fn test_matrix_init_from_string() -> Result<(), ParseMatrixError> {
let data_target = vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]];
let target = Matrix::new(data_target);
let test = Matrix::from_str("1,2,3\n4,5,6\n7,8,9")?;
assert_eq!(target, test);
Ok(())
}
#[test]
pub fn test_matrix_parse_malformed() -> () {
let malformed = "1,23,\n,567,\n\n5";
let m = Matrix::from_str(malformed);
match m {
Ok(_) => panic!("This malformed matrix string should not have succeeded"),
Err(_) => (),
}
}

View file

@ -1,8 +0,0 @@
//! Matrix-related type definitions
//!
//! Includes modules:
//! - Matrix
//! - Matrix parse and arithmetic errors
pub mod matrix;
pub mod matrix_err;