one-indexed-vec 0.2.0

A one-based (1-indexed) wrapper around Vec<T>: element at position N is accessed via vec[N].
Documentation
//! `Matrix<T>` — a dense 1-based matrix.

use crate::{Vec1, vec1};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

#[cfg(feature = "std")]
use std::vec::Vec;

/// A dense matrix with 1-based row and column indices.
///
/// Stored in row-major order. `m.get(i, j)` accesses row `i`, column `j`,
/// both starting at `1`.
///
/// ```rust
/// use one_indexed_vec::linear::matrix::Matrix;
///
/// let mut m = Matrix::new(2, 3, 0.0);
/// m.set(1, 2, 5.0);
/// assert_eq!(m.get(1, 2), 5.0);
/// assert_eq!(m.get(2, 3), 0.0);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Matrix<T> {
    data: Vec<T>,
    rows: usize,
    cols: usize,
}

impl<T: Copy + Default> Matrix<T> {
    /// Creates a `rows × cols` matrix filled with `init`.
    ///
    /// # Panics
    ///
    /// Panics if `rows == 0` or `cols == 0`.
    pub fn new(rows: usize, cols: usize, init: T) -> Self {
        assert!(rows > 0 && cols > 0, "Matrix::new: dimensions must be > 0");
        let data: Vec<T> = core::iter::repeat_n(init, rows * cols).collect();
        Matrix { data, rows, cols }
    }
}

impl<T: Copy> Matrix<T> {
    /// Constructs a matrix from a flat row-major `Vec1`.
    ///
    /// # Panics
    ///
    /// Panics if `data.len() != rows * cols`.
    pub fn from_row_major(data: Vec1<T>, rows: usize, cols: usize) -> Self {
        assert_eq!(data.len(), rows * cols, "Matrix::from_row_major: size mismatch");
        Matrix { data: data.into(), rows, cols }
    }

    /// Number of rows.
    #[inline]
    pub fn rows(&self) -> usize {
        self.rows
    }

    /// Number of columns.
    #[inline]
    pub fn cols(&self) -> usize {
        self.cols
    }

    /// Reads element at `(i, j)` (1-based).
    ///
    /// # Panics
    ///
    /// Panics if `i` or `j` is out of bounds.
    #[inline]
    pub fn get(&self, i: usize, j: usize) -> T {
        assert!(i >= 1 && i <= self.rows, "Matrix::get: row {i} out of bounds (1..={})", self.rows);
        assert!(j >= 1 && j <= self.cols, "Matrix::get: col {j} out of bounds (1..={})", self.cols);
        self.data[(i - 1) * self.cols + (j - 1)]
    }

    /// Writes element at `(i, j)` (1-based).
    ///
    /// # Panics
    ///
    /// Panics if `i` or `j` is out of bounds.
    #[inline]
    pub fn set(&mut self, i: usize, j: usize, value: T) {
        assert!(i >= 1 && i <= self.rows, "Matrix::set: row {i} out of bounds (1..={})", self.rows);
        assert!(j >= 1 && j <= self.cols, "Matrix::set: col {j} out of bounds (1..={})", self.cols);
        self.data[(i - 1) * self.cols + (j - 1)] = value;
    }

    /// Flat row-major view.
    #[inline]
    pub fn as_slice(&self) -> &[T] {
        &self.data
    }

    /// Flat row-major mutable view.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [T] {
        &mut self.data
    }

    /// Transposed copy.
    ///
    /// ```rust
    /// use one_indexed_vec::{vec1, linear::matrix::Matrix};
    ///
    /// let m = Matrix::from_row_major(vec1![1, 2, 3, 4, 5, 6], 2, 3);
    /// let t = m.transpose();
    /// assert_eq!(t.rows(), 3);
    /// assert_eq!(t.cols(), 2);
    /// assert_eq!(t.get(3, 2), 6);
    /// ```
    pub fn transpose(&self) -> Self {
        let mut out =
            Matrix { data: Vec::with_capacity(self.data.len()), rows: self.cols, cols: self.rows };
        out.data.resize(self.data.len(), self.data[0]);
        for i in 1..=self.rows {
            for j in 1..=self.cols {
                out.set(j, i, self.get(i, j));
            }
        }
        out
    }

    /// Row `i` as a 1-based vector.
    pub fn row(&self, i: usize) -> Vec1<T> {
        let mut out = Vec1::with_capacity(self.cols);
        for j in 1..=self.cols {
            out.push(self.get(i, j));
        }
        out
    }

    /// Column `j` as a 1-based vector.
    pub fn col(&self, j: usize) -> Vec1<T> {
        let mut out = Vec1::with_capacity(self.rows);
        for i in 1..=self.rows {
            out.push(self.get(i, j));
        }
        out
    }
}

impl<T> Matrix<T>
where
    T: Copy + core::ops::Add<Output = T> + core::ops::Mul<Output = T> + Default,
{
    /// Identity matrix.
    ///
    /// ```rust
    /// use one_indexed_vec::linear::matrix::Matrix;
    ///
    /// let i = Matrix::identity(3, 0.0, 1.0);
    /// assert_eq!(i.get(1, 1), 1.0);
    /// assert_eq!(i.get(1, 2), 0.0);
    /// ```
    pub fn identity(n: usize, zero: T, one: T) -> Self {
        let mut m = Matrix::new(n, n, zero);
        for i in 1..=n {
            m.set(i, i, one);
        }
        m
    }

    /// Matrix multiplication `self · other`.
    ///
    /// ```rust
    /// use one_indexed_vec::{vec1, linear::matrix::Matrix};
    ///
    /// let a = Matrix::from_row_major(vec1![1, 2, 3, 4], 2, 2);
    /// let b = Matrix::from_row_major(vec1![5, 6, 7, 8], 2, 2);
    /// let c = a.matmul(&b);
    /// assert_eq!(c.get(1, 1), 19);
    /// assert_eq!(c.get(2, 2), 50);
    /// ```
    pub fn matmul(&self, other: &Matrix<T>) -> Matrix<T> {
        assert_eq!(
            self.cols, other.rows,
            "matmul: shape mismatch ({}x{} · {}x{})",
            self.rows, self.cols, other.rows, other.cols
        );
        let mut out = Matrix::new(self.rows, other.cols, T::default());
        for i in 1..=self.rows {
            for j in 1..=other.cols {
                let mut acc = T::default();
                for k in 1..=self.cols {
                    acc = acc + self.get(i, k) * other.get(k, j);
                }
                out.set(i, j, acc);
            }
        }
        out
    }

    /// Matrix-vector product `self · v`.
    pub fn matvec(&self, v: &Vec1<T>) -> Vec1<T> {
        assert_eq!(
            self.cols,
            v.len(),
            "matvec: shape mismatch ({} cols vs {} vector)",
            self.cols,
            v.len()
        );
        let mut out = Vec1::with_capacity(self.rows);
        for i in 1..=self.rows {
            let mut acc = T::default();
            for j in 1..=self.cols {
                acc = acc + self.get(i, j) * v[j];
            }
            out.push(acc);
        }
        out
    }
}

impl<T> Matrix<T>
where
    T: Copy + core::ops::Add<Output = T> + core::ops::Sub<Output = T>,
{
    /// Element-wise addition of two same-shape matrices.
    pub fn add_matrix(&self, other: &Matrix<T>) -> Matrix<T> {
        assert!(self.rows == other.rows && self.cols == other.cols, "add_matrix: shape mismatch");
        let mut out =
            Matrix { data: Vec::with_capacity(self.data.len()), rows: self.rows, cols: self.cols };
        for k in 0..self.data.len() {
            out.data.push(self.data[k] + other.data[k]);
        }
        out
    }

    /// Element-wise subtraction.
    pub fn sub_matrix(&self, other: &Matrix<T>) -> Matrix<T> {
        assert!(self.rows == other.rows && self.cols == other.cols, "sub_matrix: shape mismatch");
        let mut out =
            Matrix { data: Vec::with_capacity(self.data.len()), rows: self.rows, cols: self.cols };
        for k in 0..self.data.len() {
            out.data.push(self.data[k] - other.data[k]);
        }
        out
    }
}

// Silence unused import warnings in some configurations.
#[allow(unused_imports)]
use vec1 as _;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vec1;

    #[test]
    fn new_get_set() {
        let mut m = Matrix::new(2, 3, 0);
        m.set(1, 2, 5);
        assert_eq!(m.get(1, 2), 5);
        assert_eq!(m.get(2, 3), 0);
    }

    #[test]
    #[should_panic(expected = "row 0 out of bounds")]
    fn get_zero_row_panics() {
        let m = Matrix::new(2, 2, 0);
        let _ = m.get(0, 1);
    }

    #[test]
    #[should_panic(expected = "col 3 out of bounds")]
    fn get_oob_col_panics() {
        let m = Matrix::new(2, 2, 0);
        let _ = m.get(1, 3);
    }

    #[test]
    fn from_row_major_roundtrip() {
        let m = Matrix::from_row_major(vec1![1, 2, 3, 4, 5, 6], 2, 3);
        assert_eq!(m.rows(), 2);
        assert_eq!(m.cols(), 3);
        assert_eq!(m.get(1, 3), 3);
        assert_eq!(m.get(2, 1), 4);
    }

    #[test]
    fn transpose_basic() {
        let m = Matrix::from_row_major(vec1![1, 2, 3, 4, 5, 6], 2, 3);
        let t = m.transpose();
        assert_eq!(t.rows(), 3);
        assert_eq!(t.cols(), 2);
        assert_eq!(t.get(1, 1), 1);
        assert_eq!(t.get(3, 2), 6);
    }

    #[test]
    fn row_col() {
        let m = Matrix::from_row_major(vec1![1, 2, 3, 4, 5, 6], 2, 3);
        assert_eq!(m.row(1).as_slice(), &[1, 2, 3]);
        assert_eq!(m.col(3).as_slice(), &[3, 6]);
    }

    #[test]
    fn matmul_basic() {
        let a = Matrix::from_row_major(vec1![1, 2, 3, 4], 2, 2);
        let b = Matrix::from_row_major(vec1![5, 6, 7, 8], 2, 2);
        let c = a.matmul(&b);
        assert_eq!(c.get(1, 1), 19);
        assert_eq!(c.get(1, 2), 22);
        assert_eq!(c.get(2, 1), 43);
        assert_eq!(c.get(2, 2), 50);
    }

    #[test]
    #[should_panic(expected = "shape mismatch")]
    fn matmul_shape_mismatch_panics() {
        let a = Matrix::new(2, 3, 0);
        let b = Matrix::new(2, 2, 0);
        let _ = a.matmul(&b);
    }

    #[test]
    fn matvec_basic() {
        let a = Matrix::from_row_major(vec1![1, 2, 3, 4], 2, 2);
        let v = vec1![1, 1];
        let out = a.matvec(&v);
        assert_eq!(out.as_slice(), &[3, 7]);
    }

    #[test]
    fn identity_basic() {
        let i = Matrix::identity(3, 0.0, 1.0);
        assert_eq!(i.get(1, 1), 1.0);
        assert_eq!(i.get(2, 2), 1.0);
        assert_eq!(i.get(1, 2), 0.0);
    }

    #[test]
    fn add_sub_matrix() {
        let a = Matrix::from_row_major(vec1![1, 2, 3, 4], 2, 2);
        let b = Matrix::from_row_major(vec1![10, 20, 30, 40], 2, 2);
        let s = a.add_matrix(&b);
        assert_eq!(s.get(1, 1), 11);
        assert_eq!(s.get(2, 2), 44);
        let d = b.sub_matrix(&a);
        assert_eq!(d.get(1, 1), 9);
        assert_eq!(d.get(2, 2), 36);
    }
}