matx 0.2.0

A lightweight, rusty matrix library that allows for simple and fast matrix operations.
Documentation
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
//! This crate is a lightweight, rusty matrix library that allows for simple (as in, easy to put into place) matrix handling and operations.

#[cfg(test)]
mod tests;

use std::{fmt::{Debug, Display, Formatter}, iter::zip};
use rand::Rng;
use std::ops;
use num::pow::*;
use serde::{Serialize, Deserialize};

#[derive(Debug, PartialEq)]
pub enum MatxError {
    SizeError,

}


/// Structure that defines a matrix. It has only two properties, a vector of values of type T that is segmented virtually when operating over the matrix, and the number of rows and columns.
#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize)]
pub struct Matrix<T> {
    data: Vec<T>,
    pub rows: usize,
    pub cols: usize
}


impl<T: Debug> Display for Matrix<T> {

    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        
        for i in 0..self.rows {
            for j in 0..self.cols {
                write!(f, "\t{:?}", self.data[i*self.cols+j]).unwrap();
            }

            writeln!(f).unwrap();
        }

        Ok(())
    }
}

impl<T: num::NumCast + Clone> Matrix<T> {
    
    /// Constructor of a new, empty matrix of numbers of size rows*cols. Every value is initialized using zeros.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::new(2, 2);
    /// // Gives: 
    /// // 0.0f64, 0.0f64
    /// // 0.0f64, 0.0f64
    /// ```
    pub fn new(rows: usize, cols: usize) -> Self {
        Self {
            data: vec![num::NumCast::from(0).unwrap(); rows*cols],
            rows,
            cols
        }
    }
}

impl<T: Default + Clone> Matrix<T> {
    
    /// Constructor of a new, empty matrix of numbers of size rows*cols. Every value is initialized using zeros.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::new(2, 2);
    /// // Gives: 
    /// // 0.0f64, 0.0f64
    /// // 0.0f64, 0.0f64
    /// ```
    pub fn empty(rows: usize, cols: usize) -> Self {
        Self {
            data: vec![T::default(); rows*cols],
            rows,
            cols
        }
    }
}

impl<T: Clone> Matrix<T> {

    pub fn map<F>(&self, f: F) -> Self 
    where F: FnMut(&T,) -> T
    {
        Self {
            data: self.data.iter().map(f).collect(),
            rows: self.rows,
            cols: self.cols
        }
    }

    /// Method that returns a `Rows` object, an iterator that iterates over rows of a matrix.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// 
    /// for r in mat.rows() {
    ///     println!("{:?}", r);
    /// }
    /// ```
    pub fn rows<'a>(&'a self) -> Rows<'a, T> {
        Rows::<'a>(self, 0)
    }

    /// Method that returns a `Columns` object, an iterator that iterates over columns of a matrix.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// 
    /// for r in mat.cols() {
    ///     println!("{:?}", r);
    /// }
    /// ```
    pub fn cols<'a>(&'a self) -> Columns<'a, T> {
        Columns::<'a>(self, 0)
    }

    /// Method to get the [row ; column] item of the matrix.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// // Building the matrix
    /// let mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// 
    /// let cell: f64 = mat.get(0, 1).unwrap();
    /// assert_eq!(cell, 3.6f64);
    /// ```
    pub fn get(&self, row: usize, column: usize) -> Option<T> {
        let index = row*self.cols + column;

        if index >= self.data.len() {
            None
        }
        else {
            Some(self.data[index].clone())
        }
    }

    /// Method to set the [row ; column] item of the matrix.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// // Building the matrix
    /// let mut mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// 
    /// mat.set(0.0f64, 0, 1);
    /// 
    /// assert_eq!(mat.get(0, 1).unwrap(), 0.0f64);
    /// ```
    pub fn set(&mut self, value: T, row: usize, column: usize) -> Result<(), &'static str> {
        let index = row*self.cols + column;

        if index >= self.data.len() {
            Err("Index out of range")
        }
        else {
            self.data[index] = value;
            Ok(())
        }
    }

    /// Method that returns a new, inverted matrix (same dimensions).
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// 
    /// // Reversing the matrix and stocking the result
    /// let rev = mat.reverse();
    /// 
    /// // What we're supposed to get
    /// let rev_ = Matrix::<f64>::from(vec![
    ///     vec![0.2f64, 1.2f64], 
    ///     vec![3.6f64, 2.0f64]
    /// ]);
    /// 
    /// assert_eq!(rev, rev_);
    /// ```
    pub fn reverse(&self) -> Self {
        Self {
            data: self.data.clone().into_iter().rev().collect(),
            rows: self.rows,
            cols: self.cols
        }
    }

}


impl <T: rand::distributions::uniform::SampleUniform> Matrix<T> {

    /// Sets all cells of the matrix to a random value in a certain range R.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// // Building the randomized matrix
    /// let mat = Matrix::<f64>::rand(5, 5, 0.0f64..10.0f64);
    /// 
    /// // Printing the matrix
    /// println!("{}", mat);
    /// ```
    pub fn rand<R: rand::distributions::uniform::SampleRange<T> + Clone>(rows: usize, cols: usize, range: R) -> Self {

        let mut rng = rand::thread_rng();

        let mut data = Vec::<T>::new();

        for _i in 0..rows*cols {
            data.push(rng.gen_range(range.clone()));
        }

        Self {
            data,
            rows,
            cols
        }
    }
}


impl<T: std::ops::Add + std::iter::Sum + Clone>  Matrix<T> {

    /// Method that returns the sum of all cells in the matrix.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// 
    /// let expected = 2.0f64 + 3.6f64 + 1.2f64 + 0.2f64;
    /// 
    /// assert_eq!(expected, mat.sum());
    /// ```
    pub fn sum(&self) -> T {
        self.data.clone().into_iter().sum()
    }
}

// Mat_a + Mat_b
impl<T> 
ops::Add<Matrix<T>> for Matrix<T> 
where T: std::ops::Add<Output = T> + num::NumCast + Clone
{

    type Output = Result<Matrix<T>, MatxError>;

    fn add(self, rhs: Matrix<T>) -> Self::Output {

        if self.rows != rhs.rows || self.cols != rhs.cols {
            Err(MatxError::SizeError)
        }
        else {

            let mut out = Matrix::<T>::new(self.rows, self.cols);

            for (i, (a, b)) in zip(self.data.iter(), rhs.data.iter()).enumerate(){
                out.data[i] = a.to_owned() + b.to_owned();
            }

            Ok(out)
        }

    }
}

// Mat_a - Mat_b
impl<T> 
ops::Sub<Matrix<T>> for Matrix<T> 
where T: std::ops::Sub<Output = T> + num::NumCast + Clone
{

    type Output = Result<Matrix<T>, MatxError>;

    fn sub(self, rhs: Matrix<T>) -> Self::Output {

        if self.rows != rhs.rows || self.cols != rhs.cols {
            Err(MatxError::SizeError)
        }
        else {

            let mut out = Matrix::<T>::new(self.rows, self.cols);

            for (i, (a, b)) in zip(self.data.iter(), rhs.data.iter()).enumerate(){
                out.data[i] = a.to_owned() - b.to_owned();
            }

            Ok(out)
        }

    }
}

// Mat_a + b
impl<T>
ops::Add<T> for Matrix<T>
where T: std::ops::Add<Output = T> + num::NumCast + Clone
{
    type Output = Matrix<T>;

    fn add(self, rhs: T) -> Self::Output {
        let mut out: Matrix<T> = Matrix::<T>::new(self.rows, self.cols);

        for (i, val) in self.data.iter().enumerate() {
                out.data[i] = val.to_owned() + rhs.clone();
        }

        out
    }
}

// Mat_a - b
impl<T>
ops::Sub<T> for Matrix<T>
where T: std::ops::Sub<Output = T> + num::NumCast + Clone
{
    type Output = Matrix<T>;

    fn sub(self, rhs: T) -> Self::Output {
        let mut out: Matrix<T> = Matrix::<T>::new(self.rows, self.cols);

        for (i, val) in self.data.iter().enumerate() {
                out.data[i] = val.to_owned() - rhs.clone();
        }

        out
    }
}

// -Mat_a
impl<T>
ops::Neg for Matrix<T> 
where T: ops::Neg<Output = T> + Clone
{
    type Output = Matrix<T>;

    fn neg(self) -> Self::Output {
        Self::Output {
            data : self.data.iter().map(|x| -x.clone()).collect(),
            rows : self.rows,
            cols : self.cols
        }
    }
}

// Mat_a ** b
impl<T>
Pow<T> for Matrix<T> 
where T: Clone + std::ops::Mul<Output = T> + Pow<T, Output = T> + num::One
{
    type Output = Matrix<T>;

    fn pow(self, rhs: T) -> Self::Output {

        Self::Output {
            data : self.data.iter().map(|x| Pow::<T>::pow(rhs.clone(), x.clone())).collect(),
            rows : self.rows,
            cols : self.cols
        }

    }
}

// Mat_a * Mat_b
impl<T> 
ops::Mul<Matrix<T>> for Matrix<T> 
where T: std::ops::Mul<Output = T> + std::ops::Add<Output = T> + num::NumCast + Clone
{

    type Output = Result<Matrix<T>, MatxError>;

    fn mul(self, rhs: Matrix<T>) -> Self::Output {
        
        if self.cols != rhs.rows {
            Err(MatxError::SizeError)
        }
        else {

            let mut out = Matrix::<T>::new(self.rows, rhs.cols);

            for i in 0..self.rows {
                for j in 0..rhs.cols {

                    for k in 0..self.cols {
                        out.data[i*rhs.cols+j] = out.data[i*rhs.cols+j].clone() + self.data[i*rhs.rows+k].clone() * rhs.data[k*rhs.cols+j].clone();
                    }
                    
                }
            }

            Ok(out)
        }
    }
}

// Mat_a * b
impl<T>
ops::Mul<T> for Matrix<T>
where T: std::ops::Mul<Output = T> + num::NumCast + Clone
{
    type Output = Matrix<T>;

    fn mul(self, rhs: T) -> Self::Output {
        let mut out: Matrix<T> = Matrix::<T>::new(self.rows, self.cols);

        for (i, val) in self.data.iter().enumerate() {
                out.data[i] = val.to_owned() * rhs.clone();
        }

        out
    }
}

// Mat_a / Mat_b
impl<T> 
ops::Div<Matrix<T>> for Matrix<T> 
where T: std::ops::Div<Output = T> + std::ops::Add<Output = T> + num::NumCast + Clone
{

    type Output = Result<Matrix<T>, MatxError>;

    fn div(self, rhs: Matrix<T>) -> Self::Output {
        
        if self.cols != rhs.rows {
            Err(MatxError::SizeError)
        }
        else {

            let mut out = Matrix::<T>::new(self.rows, rhs.cols);

            for i in 0..self.rows {
                for j in 0..rhs.cols {

                    for k in 0..self.cols {
                        out.data[i*rhs.cols+j] = out.data[i*rhs.cols+j].clone() + self.data[i*rhs.rows+k].clone() / rhs.data[k*rhs.cols+j].clone();
                    }
                    
                }
            }

            Ok(out)
        }
    }
}

// Mat_a / b
impl<T>
ops::Div<T> for Matrix<T>
where T: std::ops::Div<Output = T> + num::NumCast + Clone
{
    type Output = Matrix<T>;

    fn div(self, rhs: T) -> Self::Output {
        let mut out: Matrix<T> = Matrix::<T>::new(self.rows, self.cols);

        for (i, val) in self.data.iter().enumerate() {
                out.data[i] = val.to_owned() / rhs.clone();
        }

        out
    }
}

impl <T> From<Vec<Vec<T>>> for Matrix<T> {

    /// Creates a matrix out of a vector of vectors. ROWS and COLS must be consistent with the data provided.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// ```
    /// use matx::*;
    /// 
    /// let mat = Matrix::<f64>::from(vec![
    ///     vec![2.0f64, 3.6f64], 
    ///     vec![1.2f64, 0.2f64]
    /// ]);
    /// ```
    fn from(value: Vec<Vec<T>>) -> Self {

        let rows = value.len();
        let cols = value[0].len();

        let mut data = Vec::<T>::new();

        for mut row in value {
            assert!(row.len() == cols); // all inner vectors must have the same size
            data.append(&mut row);
        }

        Self {
            data,
            rows,
            cols
        }
    }
}

pub struct Rows<'a, T: >(&'a Matrix<T>, usize);
pub struct Columns<'a, T: >(&'a Matrix<T>, usize);


impl<T: Clone> Iterator for Columns<'_, T> {

    type Item = Vec<T>;

    fn next(&mut self) -> Option<Vec<T>> {

        if self.1*self.0.rows < self.0.data.len(){

            let mut out = Vec::<T>::new();

            for i in 0..self.0.rows {
                let index = i*self.0.rows + self.1;
                out.push(self.0.data[index].clone());
            }
            self.1 += 1;
            Some(out)
        }
        else{
            None
        }
    }
}


impl<T: Clone> Iterator for Rows<'_, T> {

    type Item = Vec<T>;

    fn next(&mut self) -> Option<Vec<T>> {

        let index = self.1*self.0.cols;

        if index < self.0.data.len(){
            self.1 += 1;
            Some(self.0.data[index..index+self.0.cols].to_owned())
        }
        else{
            None
        }
    }
}