1use std::fmt;
5use std::ops::{Add, Sub, Mul, Index};
6
7#[derive(Clone, Debug)]
9pub struct Matrix {
10 data: Vec<Vec<f64>>,
11 rows: usize,
12 cols: usize,
13}
14
15impl Matrix {
16 pub fn new(data: Vec<Vec<f64>>) -> Result<Self, String> {
18 if data.is_empty() || data[0].is_empty() {
19 return Err("Matrix cannot be empty".to_string());
20 }
21
22 let rows = data.len();
23 let cols = data[0].len();
24
25 for row in &data {
27 if row.len() != cols {
28 return Err("All rows must have the same length".to_string());
29 }
30 }
31
32 Ok(Matrix { data, rows, cols })
33 }
34
35 pub fn rows(&self) -> usize {
37 self.rows
38 }
39
40 pub fn cols(&self) -> usize {
42 self.cols
43 }
44
45 pub fn shape(&self) -> (usize, usize) {
47 (self.rows, self.cols)
48 }
49
50 pub fn data(&self) -> &Vec<Vec<f64>> {
52 &self.data
53 }
54
55 pub fn get(&self, i: usize, j: usize) -> Option<f64> {
57 self.data.get(i).and_then(|row| row.get(j).copied())
58 }
59
60 pub fn add(&self, other: &Matrix) -> Result<Matrix, String> {
62 if self.rows != other.rows || self.cols != other.cols {
63 return Err(format!(
64 "Cannot add matrices with different dimensions: ({},{}) + ({},{})",
65 self.rows, self.cols, other.rows, other.cols
66 ));
67 }
68
69 let mut result = Vec::new();
70 for i in 0..self.rows {
71 let mut row = Vec::new();
72 for j in 0..self.cols {
73 row.push(self.data[i][j] + other.data[i][j]);
74 }
75 result.push(row);
76 }
77
78 Matrix::new(result)
79 }
80
81 pub fn sub(&self, other: &Matrix) -> Result<Matrix, String> {
83 if self.rows != other.rows || self.cols != other.cols {
84 return Err(format!(
85 "Cannot subtract matrices with different dimensions: ({},{}) - ({},{})",
86 self.rows, self.cols, other.rows, other.cols
87 ));
88 }
89
90 let mut result = Vec::new();
91 for i in 0..self.rows {
92 let mut row = Vec::new();
93 for j in 0..self.cols {
94 row.push(self.data[i][j] - other.data[i][j]);
95 }
96 result.push(row);
97 }
98
99 Matrix::new(result)
100 }
101
102 pub fn scalar_mul(&self, scalar: f64) -> Result<Matrix, String> {
104 let mut result = Vec::new();
105 for i in 0..self.rows {
106 let mut row = Vec::new();
107 for j in 0..self.cols {
108 row.push(self.data[i][j] * scalar);
109 }
110 result.push(row);
111 }
112
113 Matrix::new(result)
114 }
115
116 pub fn mul(&self, other: &Matrix) -> Result<Matrix, String> {
118 if self.cols != other.rows {
119 return Err(format!(
120 "Cannot multiply matrices: ({},{}) × ({},{})",
121 self.rows, self.cols, other.rows, other.cols
122 ));
123 }
124
125 let mut result = Vec::new();
126 for i in 0..self.rows {
127 let mut row = Vec::new();
128 for j in 0..other.cols {
129 let mut value = 0.0;
130 for k in 0..self.cols {
131 value += self.data[i][k] * other.data[k][j];
132 }
133 row.push(value);
134 }
135 result.push(row);
136 }
137
138 Matrix::new(result)
139 }
140
141 fn get_minor(&self, row: usize, col: usize) -> Result<Matrix, String> {
143 let mut result = Vec::new();
144 for i in 0..self.rows {
145 if i == row {
146 continue;
147 }
148 let mut new_row = Vec::new();
149 for j in 0..self.cols {
150 if j == col {
151 continue;
152 }
153 new_row.push(self.data[i][j]);
154 }
155 result.push(new_row);
156 }
157
158 if result.is_empty() {
159 Err("Cannot compute minor of 1x1 matrix".to_string())
160 } else {
161 Matrix::new(result)
162 }
163 }
164
165 pub fn determinant(&self) -> Result<f64, String> {
167 if self.rows != self.cols {
168 return Err("Determinant only defined for square matrices".to_string());
169 }
170
171 let n = self.rows;
172
173 if n == 1 {
175 return Ok(self.data[0][0]);
176 }
177
178 if n == 2 {
180 return Ok(self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0]);
181 }
182
183 let mut det = 0.0;
185 for j in 0..n {
186 let minor = self.get_minor(0, j)?;
187 let minor_det = minor.determinant()?;
188 let sign = if j % 2 == 0 { 1.0 } else { -1.0 };
189 det += sign * self.data[0][j] * minor_det;
190 }
191
192 Ok(det)
193 }
194
195 pub fn is_square(&self) -> bool {
197 self.rows == self.cols
198 }
199
200 pub fn is_invertible(&self) -> Result<bool, String> {
202 if !self.is_square() {
203 return Ok(false);
204 }
205 let det = self.determinant()?;
206 Ok(det.abs() > 1e-10)
207 }
208
209 pub fn inverse(&self) -> Result<Matrix, String> {
211 if !self.is_invertible()? {
212 return Err("Matrix is not invertible (determinant is zero)".to_string());
213 }
214
215 let n = self.rows;
216 let det = self.determinant()?;
217
218 if n == 2 {
220 let data = vec![
221 vec![self.data[1][1] / det, -self.data[0][1] / det],
222 vec![-self.data[1][0] / det, self.data[0][0] / det],
223 ];
224 return Matrix::new(data);
225 }
226
227 let mut cofactors = Vec::new();
229 for i in 0..n {
230 let mut row = Vec::new();
231 for j in 0..n {
232 let minor = self.get_minor(i, j)?;
233 let minor_det = minor.determinant()?;
234 let sign = if (i + j) % 2 == 0 { 1.0 } else { -1.0 };
235 row.push(sign * minor_det / det);
236 }
237 cofactors.push(row);
238 }
239
240 let cofactor_matrix = Matrix::new(cofactors)?;
241 cofactor_matrix.transpose()
242 }
243
244 pub fn transpose(&self) -> Result<Matrix, String> {
246 let mut result = vec![vec![0.0; self.rows]; self.cols];
247 for i in 0..self.rows {
248 for j in 0..self.cols {
249 result[j][i] = self.data[i][j];
250 }
251 }
252 Matrix::new(result)
253 }
254
255 pub fn frobenius_norm(&self) -> f64 {
257 let mut sum = 0.0;
258 for row in &self.data {
259 for &val in row {
260 sum += val * val;
261 }
262 }
263 sum.sqrt()
264 }
265
266 pub fn trace(&self) -> Result<f64, String> {
268 if !self.is_square() {
269 return Err("Trace only defined for square matrices".to_string());
270 }
271
272 let mut sum = 0.0;
273 for i in 0..self.rows {
274 sum += self.data[i][i];
275 }
276
277 Ok(sum)
278 }
279
280 pub fn identity(n: usize) -> Result<Matrix, String> {
282 let mut data = vec![vec![0.0; n]; n];
283 for i in 0..n {
284 data[i][i] = 1.0;
285 }
286 Matrix::new(data)
287 }
288
289 pub fn zeros(rows: usize, cols: usize) -> Result<Matrix, String> {
291 if rows == 0 || cols == 0 {
292 return Err("Matrix dimensions must be positive".to_string());
293 }
294 let data = vec![vec![0.0; cols]; rows];
295 Matrix::new(data)
296 }
297
298 pub fn ones(rows: usize, cols: usize) -> Result<Matrix, String> {
300 if rows == 0 || cols == 0 {
301 return Err("Matrix dimensions must be positive".to_string());
302 }
303 let data = vec![vec![1.0; cols]; rows];
304 Matrix::new(data)
305 }
306}
307
308impl fmt::Display for Matrix {
310 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
311 writeln!(f, "Matrix ({} × {})", self.rows, self.cols)?;
312 for row in &self.data {
313 write!(f, "[")?;
314 for (i, &val) in row.iter().enumerate() {
315 if i > 0 {
316 write!(f, ", ")?;
317 }
318 write!(f, "{:8.2}", val)?;
319 }
320 writeln!(f, "]")?;
321 }
322 Ok(())
323 }
324}
325
326impl Add for &Matrix {
328 type Output = Result<Matrix, String>;
329
330 fn add(self, other: &Matrix) -> Result<Matrix, String> {
331 self.add(other)
332 }
333}
334
335impl Sub for &Matrix {
336 type Output = Result<Matrix, String>;
337
338 fn sub(self, other: &Matrix) -> Result<Matrix, String> {
339 self.sub(other)
340 }
341}
342
343impl Mul for &Matrix {
344 type Output = Result<Matrix, String>;
345
346 fn mul(self, other: &Matrix) -> Result<Matrix, String> {
347 self.mul(other)
348 }
349}
350
351impl Index<(usize, usize)> for Matrix {
352 type Output = f64;
353
354 fn index(&self, (i, j): (usize, usize)) -> &f64 {
355 &self.data[i][j]
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362
363 #[test]
364 fn test_matrix_creation() {
365 let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
366 assert_eq!(m.rows(), 2);
367 assert_eq!(m.cols(), 2);
368 }
369
370 #[test]
371 fn test_matrix_addition() {
372 let a = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
373 let b = Matrix::new(vec![vec![5.0, 6.0], vec![7.0, 8.0]]).unwrap();
374 let c = a.add(&b).unwrap();
375 assert_eq!(c[(0, 0)], 6.0);
376 assert_eq!(c[(1, 1)], 12.0);
377 }
378
379 #[test]
380 fn test_matrix_multiplication() {
381 let a = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
382 let b = Matrix::new(vec![vec![5.0, 6.0], vec![7.0, 8.0]]).unwrap();
383 let c = a.mul(&b).unwrap();
384 assert_eq!(c[(0, 0)], 19.0); assert_eq!(c[(0, 1)], 22.0); }
387
388 #[test]
389 fn test_determinant_2x2() {
390 let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
391 let det = m.determinant().unwrap();
392 assert!((det - (-2.0)).abs() < 1e-10);
393 }
394
395 #[test]
396 fn test_inverse_2x2() {
397 let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
398 let inv = m.inverse().unwrap();
399 let product = (&m * &inv).unwrap();
400 let identity = Matrix::identity(2).unwrap();
401
402 for i in 0..2 {
403 for j in 0..2 {
404 assert!((product[(i, j)] - identity[(i, j)]).abs() < 1e-10);
405 }
406 }
407 }
408
409 #[test]
410 fn test_transpose() {
411 let m = Matrix::new(vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]]).unwrap();
412 let t = m.transpose().unwrap();
413 assert_eq!(t.rows(), 3);
414 assert_eq!(t.cols(), 2);
415 assert_eq!(t[(0, 0)], 1.0);
416 assert_eq!(t[(0, 1)], 4.0);
417 }
418
419 #[test]
420 fn test_frobenius_norm() {
421 let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
422 let norm = m.frobenius_norm();
423 let expected = (1.0 + 4.0 + 9.0 + 16.0_f64).sqrt();
424 assert!((norm - expected).abs() < 1e-10);
425 }
426
427 #[test]
428 fn test_trace() {
429 let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
430 let trace = m.trace().unwrap();
431 assert_eq!(trace, 5.0);
432 }
433}