1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
//! # mini_matrix
//!
//! A mini linear algebra library implemented in Rust.
use num::{Float, Num};
use std::fmt::{Debug, Display};
use std::ops::{Add, AddAssign, Div, Mul, MulAssign, Neg, Sub, SubAssign};
use std::ops::{Deref, DerefMut, Index, IndexMut};
use crate::Vector;
/// A generic matrix type with `M` rows and `N` columns.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let matrix = Matrix::<f64, 2, 2>::from([[1.0, 2.0], [3.0, 4.0]]);
/// assert_eq!(matrix.size(), (2, 2));
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Matrix<T, const M: usize, const N: usize> {
/// The underlying storage for the matrix elements.
pub store: [[T; N]; M],
}
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default,
{
/// Creates a new `Matrix` from the given 2D array.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let matrix = Matrix::<i32, 2, 3>::from([[1, 2, 3], [4, 5, 6]]);
/// ```
pub fn from(data: [[T; N]; M]) -> Self {
Self { store: data }
}
/// Returns the dimensions of the matrix as a tuple `(rows, columns)`.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let matrix = Matrix::<f64, 3, 4>::zero();
/// assert_eq!(matrix.size(), (3, 4));
/// ```
pub const fn size(&self) -> (usize, usize) {
(M, N)
}
/// Creates a new `Matrix` with all elements set to the default value of type `T`.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let matrix = Matrix::<f64, 2, 2>::zero();
/// assert_eq!(matrix.store, [[0.0, 0.0], [0.0, 0.0]]);
/// ```
pub fn zero() -> Self {
Self {
store: [[T::default(); N]; M],
}
}
pub fn from_vecs(vecs: Vec<Vec<T>>) -> Self {
let mut store = [[T::default(); N]; M];
for (i, vec) in vecs.iter().enumerate() {
for (j, elem) in vec.iter().enumerate() {
store[i][j] = *elem;
}
}
Self { store }
}
#[allow(dead_code)]
fn map<F>(&self, mut f: F) -> Matrix<T, M, N>
where
F: FnMut(T) -> T,
{
let mut result = Matrix::<T, M, N>::zero();
for i in 0..M {
for j in 0..N {
result[(i, j)] = f(self[(i, j)]);
}
}
result
}
}
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: AddAssign + SubAssign + MulAssign + Copy + Default,
{
/// Adds another matrix to this matrix in-place.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut a = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// let b = Matrix::<i32, 2, 2>::from([[5, 6], [7, 8]]);
/// a.add(&b);
/// assert_eq!(a.store, [[6, 8], [10, 12]]);
/// ```
pub fn add(&mut self, other: &Self) {
for (l_row, r_row) in self.store.iter_mut().zip(other.store.iter()) {
for (l, r) in l_row.iter_mut().zip(r_row.iter()) {
*l += *r;
}
}
}
/// Subtracts another matrix from this matrix in-place.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut a = Matrix::<i32, 2, 2>::from([[5, 6], [7, 8]]);
/// let b = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// a.sub(&b);
/// assert_eq!(a.store, [[4, 4], [4, 4]]);
/// ```
pub fn sub(&mut self, other: &Self) {
for (l_row, r_row) in self.store.iter_mut().zip(other.store.iter()) {
for (l, r) in l_row.iter_mut().zip(r_row.iter()) {
*l -= *r;
}
}
}
/// Multiplies this matrix by a scalar value in-place.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut a = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// a.scl(2);
/// assert_eq!(a.store, [[2, 4], [6, 8]]);
/// ```
pub fn scl(&mut self, scalar: T) {
for row in self.store.iter_mut() {
for elem in row.iter_mut() {
*elem *= scalar;
}
}
}
}
impl<T, const M: usize, const N: usize> IndexMut<(usize, usize)> for Matrix<T, M, N> {
/// Mutably indexes into the matrix, allowing modification of its elements.
///
/// # Arguments
///
/// * `index` - A tuple `(row, column)` specifying the element to access.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut matrix = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// matrix[(0, 1)] = 5;
/// assert_eq!(matrix.store, [[1, 5], [3, 4]]);
/// ```
fn index_mut(&mut self, index: (usize, usize)) -> &mut T {
&mut self.store[index.0][index.1]
}
}
impl<T, const M: usize, const N: usize> Index<(usize, usize)> for Matrix<T, M, N> {
type Output = T;
/// Immutably indexes into the matrix, allowing read access to its elements.
///
/// # Arguments
///
/// * `index` - A tuple `(row, column)` specifying the element to access.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let matrix = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// assert_eq!(matrix[(1, 0)], 3);
/// ```
fn index(&self, index: (usize, usize)) -> &Self::Output {
&self.store.index(index.0).index(index.1)
}
}
impl<T, const M: usize, const N: usize> Deref for Matrix<T, M, N> {
type Target = [[T; N]; M];
/// Dereferences the matrix, allowing it to be treated as a slice.
///
/// # Note
///
/// This implementation is currently unfinished.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let matrix = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// // Usage example will be available once implementation is complete
/// ```
fn deref(&self) -> &Self::Target {
&self.store
}
}
impl<T, const M: usize, const N: usize> DerefMut for Matrix<T, M, N> {
/// Mutably dereferences the matrix, allowing it to be treated as a mutable slice.
///
/// # Note
///
/// This implementation is currently unfinished.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut matrix = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// // Usage example will be available once implementation is complete
/// ```
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.store
}
}
impl<T, const M: usize, const N: usize> Add for Matrix<T, M, N>
where
T: AddAssign + Copy + Num,
{
type Output = Self;
/// Adds two matrices element-wise.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// let b = Matrix::<i32, 2, 2>::from([[5, 6], [7, 8]]);
/// let c = a + b;
/// assert_eq!(c.store, [[6, 8], [10, 12]]);
/// ```
fn add(self, rhs: Self) -> Self::Output {
let mut result = self.clone();
for (l_row, r_row) in result.store.iter_mut().zip(rhs.store.iter()) {
for (l, r) in l_row.iter_mut().zip(r_row.iter()) {
*l += *r;
}
}
result
}
}
impl<T, const M: usize, const N: usize> Sub for Matrix<T, M, N>
where
T: SubAssign + Copy + Num,
{
type Output = Self;
/// Subtracts one matrix from another element-wise.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 2, 2>::from([[5, 6], [7, 8]]);
/// let b = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// let c = a - b;
/// assert_eq!(c.store, [[4, 4], [4, 4]]);
/// ```
fn sub(self, rhs: Self) -> Self::Output {
let mut result = self.clone();
for (l_row, r_row) in result.store.iter_mut().zip(rhs.store.iter()) {
for (l, r) in l_row.iter_mut().zip(r_row.iter()) {
*l -= *r;
}
}
result
}
}
impl<T, const M: usize, const N: usize> Mul<T> for Matrix<T, M, N>
where
T: MulAssign + Copy + Num,
{
type Output = Self;
/// Multiplies a matrix by a scalar value.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// let b = a * 2;
/// assert_eq!(b.store, [[2, 4], [6, 8]]);
/// ```
fn mul(self, rhs: T) -> Self::Output {
let mut result = self.clone();
for row in result.store.iter_mut() {
for elem in row.iter_mut() {
*elem *= rhs;
}
}
result
}
}
impl<T, const M: usize, const N: usize> Mul<Vector<T, N>> for Matrix<T, M, N>
where
T: MulAssign + AddAssign + Copy + Num + Default,
{
type Output = Vector<T, M>;
/// Multiplies a matrix by a vector.
///
/// # Examples
///
/// ```
/// use mini_matrix::{Matrix, Vector};
///
/// let a = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// let v = Vector::<i32, 2>::from([5, 6]);
/// let result = a * v;
/// assert_eq!(result.store, [17, 39]);
/// ```
fn mul(self, rhs: Vector<T, N>) -> Self::Output {
let mut result = Vector::zero();
for (idx, row) in self.store.iter().enumerate() {
for (e1, e2) in row.iter().zip(rhs.store.iter()) {
result.store[idx] += *e1 * *e2;
}
}
result
}
}
impl<T, const M: usize, const N: usize> Mul<Matrix<T, N, N>> for Matrix<T, M, N>
where
T: MulAssign + AddAssign + Copy + Num + Default,
{
type Output = Self;
/// Multiplies two matrices.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 2, 2>::from([[1, 2], [3, 4]]);
/// let b = Matrix::<i32, 2, 2>::from([[5, 6], [7, 8]]);
/// let c = a * b;
/// assert_eq!(c.store, [[17, 23], [39, 53]]);
/// ```
fn mul(self, rhs: Matrix<T, N, N>) -> Self::Output {
let mut result = Matrix::zero();
for (i, row) in self.store.iter().enumerate() {
for (j, col) in rhs.store.iter().enumerate() {
for (e1, e2) in row.iter().zip(col.iter()) {
result.store[i][j] += *e1 * *e2;
}
}
}
result
}
}
impl<T, const M: usize, const N: usize> Neg for Matrix<T, M, N>
where
T: Neg<Output = T> + Copy,
{
type Output = Self;
/// Negates all elements of the matrix.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 2, 2>::from([[1, -2], [-3, 4]]);
/// let b = -a;
/// assert_eq!(b.store, [[-1, 2], [3, -4]]);
/// ````
fn neg(self) -> Self::Output {
let mut result = self.clone();
for row in result.store.iter_mut() {
for elem in row.iter_mut() {
*elem = -*elem;
}
}
result
}
}
impl<T, const M: usize, const N: usize> Display for Matrix<T, M, N>
where
T: AddAssign + SubAssign + MulAssign + Copy + std::fmt::Display,
{
/// Formats the matrix for display.
///
/// Each row of the matrix is displayed on a new line, with elements separated by commas.
/// Elements are formatted with one decimal place precision.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<f32, 2, 2>::from([[1.0, 2.5], [3.7, 4.2]]);
/// println!("{}", a);
/// // Output:
/// // // [1.0, 2.5]
/// // // [3.7, 4.2]
/// ```
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
for (i, row) in self.store.iter().enumerate() {
if i > 0 {
writeln!(f)?;
}
write!(f, "// [")?;
for (j, val) in row.iter().enumerate() {
if j > 0 {
write!(f, ", ")?;
}
write!(f, "{:.1}", val)?;
}
write!(f, "]")?;
}
write!(f, "\n")?;
Ok(())
}
}
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Num + Copy + AddAssign + Default,
{
/// Multiplies the matrix by a vector.
///
/// # Arguments
/// * `vec` - The vector to multiply with the matrix.
///
/// # Returns
/// The resulting vector of the multiplication.
pub fn mul_vec(&mut self, vec: &Vector<T, N>) -> Vector<T, N> {
let mut result = Vector::zero();
for (idx, row) in self.store.iter_mut().enumerate() {
for (e1, e2) in row.iter_mut().zip(vec.store.iter()) {
result[idx] += *e1 * *e2;
}
}
result
}
/// Multiplies the matrix by another matrix.
///
/// # Arguments
/// * `mat` - The matrix to multiply with.
///
/// # Returns
/// The resulting matrix of the multiplication.
pub fn mul_mat(&mut self, mat: &Matrix<T, M, N>) -> Matrix<T, M, N> {
let mut result = Matrix::zero();
for i in 0..M {
for j in 0..N {
for k in 0..N {
result[(i, j)] += self[(i, k)] * mat[(k, j)];
}
}
}
result
}
}
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Num + Copy + AddAssign + Default,
{
/// Calculates the trace of the matrix.
///
/// The trace is defined as the sum of the elements on the main diagonal.
///
/// # Panics
///
/// Panics if the matrix is not square (i.e., if M != N).
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut a = Matrix::<i32, 3, 3>::from([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
/// assert_eq!(a.trace(), 15);
/// ```
pub fn trace(&self) -> T {
assert!(M == N, "Matrix must be square to calculate trace");
let mut result = T::default();
for i in 0..M {
result += self[(i, i)];
}
result
}
}
/* ********************************************* */
/* Exercise 09 - Transpose */
/* ********************************************* */
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default,
{
/// Computes the transpose of the matrix.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let mut a = Matrix::<i32, 2, 3>::from([[1, 2, 3], [4, 5, 6]]);
/// let b = a.transpose();
/// assert_eq!(b.store, [[1, 4], [2, 5], [3, 6]]);
/// ```
pub fn transpose(&mut self) -> Matrix<T, N, M> {
let mut result = Matrix::zero();
for i in 0..M {
for j in 0..N {
result[(j, i)] = self[(i, j)];
}
}
result
}
}
/* ********************************************** */
/* Exercise XX - Identity */
/* ********************************************** */
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default + Num,
{
/// Creates an identity matrix.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 3, 3>::identity();
/// assert_eq!(a.store, [[1, 0, 0], [0, 1, 0], [0, 0, 1]]);
/// ```
pub fn identity() -> Matrix<T, M, N> {
let mut result = Matrix::zero();
for i in 0..M {
result[(i, i)] = T::one();
}
result
}
}
/* ************************************************* */
/* Exercise 12 - Row Echelon */
/* ************************************************* */
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default + Mul<Output = T> + PartialEq + Num + Div<Output = T> + Sub<Output = T>,
{
/// Converts a given matrix to its Reduced Row-Echelon Form (RREF).
///
/// Row-echelon form is a specific form of a matrix that is particularly useful for solving
/// systems of linear equations and for understanding the properties of the matrix. To explain
/// it simply and in detail, let's go through what row-echelon form is, how to achieve it, and
/// an example to illustrate the process.
///
/// # Row-Echelon Form
///
/// A matrix is in row-echelon form if it satisfies the following conditions:
///
/// 1. **Leading Entry**: The leading entry (first non-zero number from the left) in each row is 1.
/// This is called the pivot.
/// 2. **Zeros Below**: The pivot in each row is to the right of the pivot in the row above, and
/// all entries below a pivot are zeros.
/// 3. **Rows of Zeros**: Any rows consisting entirely of zeros are at the bottom of the matrix.
///
/// # Reduced Row-Echelon Form
///
/// A matrix is in reduced row-echelon form (RREF) if it additionally satisfies:
///
/// 4. **Leading Entries**: Each leading 1 is the only non-zero entry in its column.
///
/// # Achieving Row-Echelon Form
///
/// To convert a matrix into row-echelon form, we use a process called Gaussian elimination.
/// This involves performing row operations:
///
/// 1. **Row swapping**: Swapping the positions of two rows.
/// 2. **Row multiplication**: Multiplying all entries of a row by a non-zero scalar.
/// 3. **Row addition**: Adding or subtracting the multiples of one row to another row.
///
///
/// Let's consider an example with a `3 x 3` matrix:
///
///
/// A = [
/// [1, 2, 3],
/// [4, 5, 6],
/// [7, 8, 9]
/// ]
///
/// ## Step-by-Step Process
///
/// 1. **Starting Matrix**:
///
/// [
/// [1, 2, 3],
/// [4, 5, 6],
/// [7, 8, 9]
/// ]
///
/// 2. **Make the Pivot of Row 1 (already 1)**:
///
/// The first leading entry is already 1.
///
/// 3. **Eliminate Below Pivot in Column 1**:
///
/// Subtract 4 times the first row from the second row:
///
/// R2 = R2 - 4R1
/// [
/// [1, 2, 3],
/// [0, -3, -6],
/// [7, 8, 9]
/// ]
///
/// Subtract 7 times the first row from the third row:
///
/// R3 = R3 - 7R1
/// [
/// [1, 2, 3],
/// [0, -3, -6],
/// [0, -6, -12]
/// ]
///
/// 4. **Make the Pivot of Row 2**:
///
/// Divide the second row by -3 to make the pivot 1:
///
/// R2 = (1 / -3) * R2
/// [
/// [1, 2, 3],
/// [0, 1, 2],
/// [0, -6, -12]
/// ]
///
/// 5. **Eliminate Below Pivot in Column 2**:
///
/// Add 6 times the second row to the third row:
///
/// R3 = R3 + 6R2
/// [
/// [1, 2, 3],
/// [0, 1, 2],
/// [0, 0, 0]
/// ]
///
/// Now, the matrix is in row-echelon form.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<f64, 3, 4>::from([
/// [1.0, 2.0, 3.0, 4.0],
/// [5.0, 6.0, 7.0, 8.0],
/// [9.0, 10.0, 11.0, 12.0]
/// ]);
/// let b = a.row_echelon();
/// // Check the result (approximate due to floating-point arithmetic)
/// ```
// pub fn row_echelon(&self) -> Matrix<T, M, N> {
// let mut result = self.clone();
// let mut pivot = 0;
// for r in 0..M {
// if pivot >= N {
// break;
// }
// // Find the row with a non-zero pivot
// let mut i = r;
// while i < M && result[(i, pivot)] == T::default() {
// i += 1;
// }
// if i == M {
// pivot += 1;
// if pivot >= N {
// break;
// }
// // No non-zero element found in this column, continue to the next column
// continue;
// }
// // Swap the current row with the row containing the non-zero pivot
// if i != r {
// for j in 0..N {
// let temp = result[(r, j)];
// result[(r, j)] = result[(i, j)];
// result[(i, j)] = temp;
// }
// }
// // Normalize the pivot row
// let divisor = result[(r, pivot)];
// if divisor != T::default() {
// for j in 0..N {
// result[(r, j)] = result[(r, j)] / divisor;
// }
// }
// // Eliminate the pivot column in all other rows
// for i in 0..M {
// if i != r {
// let factor = result[(i, pivot)];
// for j in 0..N {
// result[(i, j)] = result[(i, j)] - factor * result[(r, j)];
// }
// }
// }
// pivot += 1;
// }
// result
// }
pub fn row_echelon(&self) -> Matrix<T, M, N> {
let mut result = self.clone();
// let mut matrix_out = result.store;
let mut pivot = 0;
let row_count = M;
let column_count = N;
'outer: for r in 0..row_count {
if column_count <= pivot {
break;
}
let mut i = r;
while result[(i, pivot)] == T::default() {
i = i + 1;
if i == row_count {
i = r;
pivot = pivot + 1;
if column_count == pivot {
pivot = pivot - 1;
break 'outer;
}
}
}
for j in 0..row_count {
let temp = result[(r, j)];
result[(r, j)] = result[(i, j)];
result[(i, j)] = temp;
}
let divisor = result[(r, pivot)];
if divisor != T::default() {
for j in 0..column_count {
result[(r, j)] = result[(r, j)] / divisor;
}
}
for j in 0..row_count {
if j != r {
let hold = result[(j, pivot)];
for k in 0..column_count {
result[(j, k)] = result[(j, k)] - (hold * result[(r, k)]);
}
}
}
pivot = pivot + 1;
}
result
}
}
/************************************************ * */
/* Exercise 12 - Determinant */
/************************************************ */
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default + Mul + Num + Neg<Output = T> + AddAssign + Debug,
{
/// Computes the determinant of the matrix.
///
/// # Determinant in General
///
/// The determinant is a scalar value that can be computed from the elements of a square matrix.
/// It provides important properties about the matrix and the linear transformation it represents.
/// In general, the determinant represents the scaling factor of the volume when the matrix is
/// used as a linear transformation. It can be positive, negative, or zero, each with different
/// implications:
///
/// - **\(\det(A) = 0\)**:
/// - The matrix `A` is **singular** and does not have an inverse.
/// - The columns (or rows) of `A` are linearly dependent.
/// - The transformation collapses the space into a lower-dimensional subspace.
/// - Geometrically, it indicates that the volume of the transformed space is 0.
///
/// - **\(\det(A) > 0\)**:
/// - The matrix `A` is **non-singular** and has an inverse.
/// - The transformation preserves the orientation of the space.
/// - Geometrically, it indicates a positive scaling factor of the volume.
///
/// - **\(\det(A) < 0\)**:
/// - The matrix `A` is **non-singular** and has an inverse.
/// - The transformation reverses the orientation of the space.
/// - Geometrically, it indicates a negative scaling factor of the volume.
///
/// # Example
///
/// Consider a `2 x 2` matrix:
///
/// ```text
/// A = [
/// [1, 2],
/// [3, 4]
/// ]
/// ```
///
/// The determinant is:
///
/// ```text
/// det(A) = 1 * 4 - 2 * 3 = 4 - 6 = -2
/// ```
///
/// This indicates that the transformation represented by `A` scales areas by a factor of 2 and
/// reverses their orientation.
///
/// # Panics
///
/// Panics if the matrix size is larger than `4 x 4`.
///
/// # Returns
///
/// The determinant of the matrix.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 3, 3>::from([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
/// assert_eq!(a.determinant(), 0);
/// ```
pub fn determinant(&self) -> T {
match M {
1 => self[(0, 0)],
2 => self[(0, 0)] * self[(1, 1)] - self[(0, 1)] * self[(1, 0)],
3 => self.determinant_3x3(),
4 => (0..4)
.map(|i| {
let sign = if i % 2 == 0 { T::one() } else { -T::one() };
let cofactor = self.get_cofactor(0, i);
sign * self[(0, i)] * cofactor.determinant_3x3()
})
.fold(T::default(), |acc, x| acc + x),
_ => panic!("Determinant not implemented for matrices larger than 4x4"),
}
}
fn determinant_3x3(&self) -> T {
self[(0, 0)] * (self[(1, 1)] * self[(2, 2)] - self[(1, 2)] * self[(2, 1)])
- self[(0, 1)] * (self[(1, 0)] * self[(2, 2)] - self[(1, 2)] * self[(2, 0)])
+ self[(0, 2)] * (self[(1, 0)] * self[(2, 1)] - self[(1, 1)] * self[(2, 0)])
}
fn get_cofactor(&self, row: usize, col: usize) -> Matrix<T, 3, 3> {
let mut cofactor_matrix = Matrix::<T, 3, 3>::zero();
let mut row_index = 0;
for r in 0..M {
if r == row {
continue;
}
let mut col_index = 0;
for c in 0..N {
if c == col {
continue;
}
cofactor_matrix[(row_index, col_index)] = self[(r, c)];
col_index += 1;
}
row_index += 1;
}
cofactor_matrix
}
}
/********************************************* */
/* Exercise 12 - Inverse */
/********************************************* */
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default + Mul + Num + Neg<Output = T> + AddAssign + Debug + Float,
{
/// Calculates the inverse of the matrix.
///
/// This method supports matrices up to 3x3 in size.
///
/// # Returns
///
/// Returns `Ok(Matrix)` if the inverse exists, or an `Err` with a descriptive message if not.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<f64, 2, 2>::from([[1.0, 2.0], [3.0, 4.0]]);
/// let inv = a.inverse().unwrap();
/// // Check the result (approximate due to floating-point arithmetic)
/// ```
pub fn inverse(&self) -> Result<Self, &'static str> {
if M != N {
return Err("Matrix must be square to calculate inverse");
}
let det = self.determinant();
if det == T::zero() {
return Err("Matrix is singular and has no inverse");
}
let mut inv = Matrix::<T, N, M>::zero();
for i in 0..M {
for j in 0..N {
let coffactor = match M {
2 => self.cofactor1x1(i, j).determinant(),
3 => self.cofactor2x2(i, j).determinant(),
_ => return Err("Inverse not implemented for matrices larger than 3x3"),
};
let base: i32 = -1;
inv[(i, j)] = (coffactor * T::from(base.pow((i + j) as u32)).unwrap()) / det;
}
}
let inv = inv.transpose();
Ok(inv)
}
}
/***************************************** */
/* Exercise 13 - Rank */
/***************************************** */
impl<T, const M: usize, const N: usize> Matrix<T, M, N>
where
T: Copy + Default + Mul + Num + Neg<Output = T> + AddAssign + PartialEq,
{
/// Calculates the rank of the matrix.
///
/// The rank is determined by computing the row echelon form and counting non-zero rows.
///
/// # Examples
///
/// ```
/// use mini_matrix::Matrix;
///
/// let a = Matrix::<i32, 3, 3>::from([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);
/// assert_eq!(a.rank(), 2);
/// ```
pub fn rank(&self) -> usize {
let mut rank = M;
let row_echelon = self.row_echelon();
for i in 0..M {
let mut is_zero = true;
for j in 0..N {
if row_echelon[(i, j)] != T::default() {
is_zero = false;
break;
}
}
if is_zero {
rank -= 1;
}
}
rank
}
}