Skip to main content

Matrix

Struct Matrix 

Source
pub struct Matrix { /* private fields */ }
Expand description

Row-major dense matrix of f64 backed by a single contiguous Vec<f64>.

The flat layout (one allocation, stride-1 row traversal) keeps every numeric hot loop cache-friendly and auto-vectorizable — a substantial speedup over the previous Vec<Vec<f64>> representation on large dense inputs.

§Examples

use datarust::Matrix;

let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
assert_eq!(m.nrows(), 2);
assert_eq!(m.ncols(), 2);
assert_eq!(m.get(0, 0), 1.0);

Implementations§

Source§

impl Matrix

Source

pub fn new(data: Vec<Vec<f64>>) -> Result<Self>

Creates a matrix from a nested vector, validating a rectangular shape.

Source

pub fn from_rows(rows: Vec<Vec<f64>>) -> Result<Self>

Creates a matrix from a nested vector of rows.

Source

pub fn from_flat(rows: usize, cols: usize, flat: Vec<f64>) -> Result<Self>

Creates a matrix from row-major flat data of the given shape.

With the flat internal representation this stores the buffer directly, with no per-row chunking or copy.

use datarust::Matrix;

let m = Matrix::from_flat(2, 3, vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
assert_eq!(m.nrows(), 2);
assert_eq!(m.ncols(), 3);
assert_eq!(m.get(1, 2), 6.0);
Source

pub fn zeros(rows: usize, cols: usize) -> Result<Self>

Creates a matrix filled with zeros of the given shape.

Source

pub fn identity(n: usize) -> Result<Self>

Creates an n by n identity matrix.

Source

pub fn nrows(&self) -> usize

Returns the number of rows.

Source

pub fn ncols(&self) -> usize

Returns the number of columns.

Source

pub fn as_slice(&self) -> &[f64]

Returns the underlying flat row-major data as a slice.

Elements are laid out so that element (i, j) is at index i * ncols + j. Use this for cache-friendly, auto-vectorizable numeric loops in preference to per-element get calls.

Source

pub fn as_mut_slice(&mut self) -> &mut [f64]

Returns the underlying flat row-major data as a mutable slice.

Source

pub fn get(&self, i: usize, j: usize) -> f64

Returns the element at row i, column j.

§Panics

Panics if i >= nrows() or j >= ncols(). Use checked_get for a safe alternative that returns None on out-of-bounds access.

Source

pub fn checked_get(&self, i: usize, j: usize) -> Option<f64>

Returns Some(element) at row i, column j, or None if the indices are out of bounds.

Source

pub fn set(&mut self, i: usize, j: usize, v: f64)

Sets the element at row i, column j.

Source

pub fn validate_no_nan(&self) -> Result<()>

Returns Ok(()) if the matrix contains no NaN values.

Source

pub fn validate_finite(&self) -> Result<()>

Returns Ok(()) if every matrix element is finite.

Unlike validate_no_nan, this also rejects positive and negative infinity. Algorithms whose numerical kernels do not define missing-value semantics should call this before fitting or predicting.

Source

pub fn validate_no_infinite(&self) -> Result<()>

Returns Ok(()) if the matrix contains no positive or negative infinity. NaN values are allowed for missing-value-aware algorithms such as imputers.

Source

pub fn row(&self, i: usize) -> &[f64]

Returns the row at index i as a contiguous slice.

use datarust::Matrix;

let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
assert_eq!(m.row(0), &[1.0, 2.0]);
Source

pub fn col(&self, j: usize) -> Vec<f64>

Returns column j as a new vector.

use datarust::Matrix;

let m = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
assert_eq!(m.col(1), vec![2.0, 4.0]);
Source

pub fn iter_rows(&self) -> impl Iterator<Item = &[f64]>

Iterates over the rows as contiguous slices.

Source

pub fn transpose(&self) -> Matrix

Returns the transpose of the matrix.

use datarust::Matrix;

let m = Matrix::new(vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]]).unwrap();
let t = m.transpose();
assert_eq!(t.nrows(), 3);
assert_eq!(t.ncols(), 2);
assert_eq!(t.get(0, 1), 4.0);
Source

pub fn matmul(&self, other: &Matrix) -> Result<Matrix>

Multiplies two matrices and returns the product.

use datarust::Matrix;

let a = Matrix::new(vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
let b = Matrix::new(vec![vec![5.0, 6.0], vec![7.0, 8.0]]).unwrap();
let c = a.matmul(&b).unwrap();
assert_eq!(c.get(0, 0), 19.0); // 1*5 + 2*7
assert_eq!(c.get(0, 1), 22.0); // 1*6 + 2*8
Source

pub fn column_mean(&self) -> Vec<f64>

Returns the mean of each column.

Source

pub fn from_columns(cols: Vec<Vec<f64>>) -> Result<Self>

Creates a matrix from a vector of columns.

Source

pub fn select_columns(&self, indices: &[usize]) -> Result<Self>

Select a subset of columns by index (0-based).

use datarust::Matrix;

let m = Matrix::new(vec![
    vec![1.0, 2.0, 3.0],
    vec![4.0, 5.0, 6.0],
])?;
let sub = m.select_columns(&[0, 2])?;
assert_eq!(sub.ncols(), 2);
assert_eq!(sub.get(0, 0), 1.0);
assert_eq!(sub.get(0, 1), 3.0);
Source

pub fn select_rows(&self, indices: &[usize]) -> Result<Self>

Select a subset of rows by index (0-based).

use datarust::Matrix;

let m = Matrix::new(vec![
    vec![10.0],
    vec![20.0],
    vec![30.0],
])?;
let sub = m.select_rows(&[0, 2])?;
assert_eq!(sub.nrows(), 2);
assert_eq!(sub.get(0, 0), 10.0);
assert_eq!(sub.get(1, 0), 30.0);

Trait Implementations§

Source§

impl Clone for Matrix

Source§

fn clone(&self) -> Matrix

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Matrix

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Matrix

Available on crate feature serde only.
Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for Matrix

Source§

fn eq(&self, other: &Matrix) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Matrix

Available on crate feature serde only.
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Matrix

Source§

impl TryFrom<Vec<Vec<f64>>> for Matrix

Source§

fn try_from(data: Vec<Vec<f64>>) -> Result<Self>

Fallibly construct a Matrix from a nested vector.

Returns an error if the rows are empty or jagged. This replaces the previous panicking From impl to keep validation consistent with Matrix::new.

Source§

type Error = DatarustError

The type returned in the event of a conversion error.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.