From 601c1c58d05353433e8ad17169df7681640c8484 Mon Sep 17 00:00:00 2001 From: Palash Tyagi <23239946+Magnus167@users.noreply.github.com> Date: Thu, 24 Apr 2025 23:33:04 +0100 Subject: [PATCH] Refactor element-wise comparison implementation for matrices --- src/matrix/mat.rs | 41 +++++++++++++++++++---------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/src/matrix/mat.rs b/src/matrix/mat.rs index c04873c..2e9d5a6 100644 --- a/src/matrix/mat.rs +++ b/src/matrix/mat.rs @@ -184,30 +184,27 @@ impl<'a, T> MatrixRow<'a, T> { } } -// PartialEq for element-wise comparison -impl Matrix { - /// Performs element-wise equality comparison with another matrix. - /// Returns a new `Matrix` where each element is the result of comparing the corresponding elements. - /// Panics if the matrices have different dimensions. - pub fn eq_elementwise(&self, rhs: &Matrix) -> BoolMatrix { - assert_eq!( - self.rows, rhs.rows, - "Matrices must have the same number of rows for element-wise comparison" - ); - assert_eq!( - self.cols, rhs.cols, - "Matrices must have the same number of columns for element-wise comparison" - ); +macro_rules! impl_cmp { + ($name:ident, $op:tt) => { + pub fn $name(&self, rhs: &Matrix) -> BoolMatrix { + assert_eq!(self.rows, rhs.rows, "…"); + assert_eq!(self.cols, rhs.cols, "…"); - let data = self - .data - .iter() - .zip(rhs.data.iter()) - .map(|(a, b)| a == b) // Use T::PartialEq::eq - .collect(); + let data = self.data.iter() + .zip(rhs.data.iter()) + .map(|(a, b)| a $op b) + .collect(); - BoolMatrix::from_vec(data, self.rows, self.cols) - } + BoolMatrix::from_vec(data, self.rows, self.cols) + } + }; +} + +impl Matrix { + impl_cmp!(lt_elementwise, <); + impl_cmp!(le_elementwise, <=); + impl_cmp!(gt_elementwise, >); + impl_cmp!(ge_elementwise, >=); } /// Generates element-wise arithmetic implementations for matrices.