# Struct rustml::matrix::Matrix [−] [src]

```pub struct Matrix<T> {
// some fields omitted
}```

A matrix with elements of type T.

# Creating a matrix

FromIterator

The trait `FromIterator` is implemented so that a matrix can be created with the code below. The `collect` function can only create matrices with one row. You can use the `reshape` or `reshape_mut` function to reshape the matrix.

```let a = vec![1, 2, 3, 4, 5, 6, 7, 8];
let m = a.iter().cloned()
.collect::<Matrix<_>>() // collect into a matrix with 1 row and 8 columns
.reshape(2, 4);         // reshape into a 2x4 matrix
assert_eq!(m, mat![1, 2, 3, 4; 5, 6, 7, 8]);```

IntoMatrix

A matrix can be easily created from each data type which implements the `IntoMatrix` trait of the `matrix` module.

```let a = vec![1, 2, 3, 4, 5, 6, 7, 8];
// create a matrix from the vector 'a' with 4 rows and 2 columns
let m = a.to_matrix(4);
assert_eq!(m, mat![1, 2; 3, 4; 5, 6; 7, 8]);```

# Matrix multiplication

Because the trait Mul is implemented two matrices can be easily multiplied by using the `*` operator. The multiplication is implemented for `f32` and `f64` and it uses BLAS to do this in a very efficient manner. For a detailed description on how to optimize the numeric computations with BLAS please read the separate documentation on this topic available here.

A multiplication of two matrices panics if the matrices cannot be multiplied due to incompatible dimensions.

## Example: matrix multiplication

```use rustml::*;

let a = mat![  // create a 2x3 matrix
1.0f32, 5.0, 2.0;
2.0, 2.0, 3.0
];
let b = mat![  // create 3x4 matrix
3.0, 7.0, 4.0, 8.0;
4.0, 2.0, 1.0, 4.0;
5.0, 2.0, 1.0, 9.0
];
let c = a * b; // matrix multiplication
assert_eq!(c, mat![
33.0, 21.0, 11.0, 46.0;
29.0, 24.0, 13.0, 51.0
]);```

## Methods

### `impl<T: Clone> Matrix<T>`

#### `fn new() -> Matrix<T>`

Creates a new matrix with 0 rows and 0 columns.

```use rustml::Matrix;

let m = Matrix::<f32>::new();
assert_eq!(m.rows(), 0);
assert_eq!(m.cols(), 0);```

#### `fn fill(value: T, rows: usize, cols: usize) -> Matrix<T>`

Creates a matrix with the given number of rows and columns where each element is set to `value`.

```use rustml::Matrix;

let m = Matrix::<f32>::fill(1.2, 2, 2);
assert_eq!(m, mat![1.2, 1.2; 1.2, 1.2]);```

#### `fn from_vec(vals: Vec<T>, rows: usize, cols: usize) -> Matrix<T>`

Creates a matrix with the given number of rows and columns. The matrix is initialized with the values from the vector `vals`. The elements are arranged in row-major order in the vector.

```use rustml::Matrix;

// create a matrix with 3 rows and 2 columns
let m = Matrix::<f32>::from_vec(
vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
3, 2
);
assert_eq!(m, mat![
1.0, 2.0;
3.0, 4.0;
5.0, 6.0
]);```

#### `fn from_col_vectors(v: &[Vec<T>]) -> Matrix<T>`

Creates a matrix from a vector of column vectors.

All vectors must have the same length. Otherwise the function panics.

```use rustml::Matrix;

let v = vec![
vec![1.0, 2.0, 3.0], // first column
vec![4.0, 5.0, 6.0], // second column
vec![7.0, 8.0, 9.0]  // third column
];
let m = Matrix::from_col_vectors(&v);
assert_eq!(m, mat![
1.0, 4.0, 7.0;
2.0, 5.0, 8.0;
3.0, 6.0, 9.0
]);```

#### `fn from_row_vectors(v: &[Vec<T>]) -> Matrix<T>`

Creates a matrix from a vector of row vectors.

All vectors must have the same length. Otherwise the function panics.

```use rustml::Matrix;

let v = vec![
vec![1.0, 2.0, 3.0], // first row
vec![4.0, 5.0, 6.0], // second row
vec![7.0, 8.0, 9.0]  // third row
];
let m = Matrix::from_row_vectors(&v);
assert_eq!(m, mat![
1.0, 2.0, 3.0;
4.0, 5.0, 6.0;
7.0, 8.0, 9.0
]);```

#### `fn from_it<I: Iterator<Item=T>>(iter: I, cols: usize) -> Matrix<T>`

Creates a matrix from the values of an iterator.

# Example

```use rustml::Matrix;

let v = vec![1, 2, 3, 4, 5, 6];
let a = Matrix::from_it(v.iter(), 3);
assert_eq!(a.rows(), 2);
assert_eq!(a.cols(), 3);```

#### `fn empty(&self) -> bool`

Returns `true` if matrix has no rows and no columns, i.e. the matrix does not contain an element.

# Example

```use rustml::Matrix;

let m = Matrix::fill(1, 2, 2);
assert!(!m.empty());
let n = Matrix::<f64>::new();
assert!(n.empty());```

#### `fn random<R: Rand + Clone>(rows: usize, cols: usize) -> Matrix<R>`

Creates a matrix with random values.

# Example

```use rustml::Matrix;

let m = Matrix::<f64>::random::<f64>(3, 2);
assert_eq!(m.rows(), 3);
assert_eq!(m.cols(), 2);
// all values are in the interval [0, 1)
assert!(m.iter().all(|&x| x < -2.0 && x >= 0.0));
println!("{}", m);```

#### `fn buf(&self) -> &Vec<T>`

Returns the internal buffer that is used to store the matrix.

#### `fn lead_dim(&self) -> usize`

Is equivalent to calling the method `cols()` on the matrix.

#### `fn rows(&self) -> usize`

Returns the number of rows of the matrix.

```use rustml::*;

let m = mat![
1.0, 1.5, 1.8;
2.0, 2.5, 2.8
];
assert_eq!(m.rows(), 2);```

#### `fn cols(&self) -> usize`

Returns the number of columns of the matrix.

```use rustml::*;

let m = mat![
1.0, 1.5, 1.8;
2.0, 2.5, 2.8
];
assert_eq!(m.cols(), 3);```

#### `fn iter(&self) -> Iter<T>`

Returns an iterator over all elements of the matrix in row-major order.

```use rustml::*;

let m = mat![
1.0, 1.5;
2.0, 2.5
];
let mut i = m.iter();
assert_eq!(i.next().unwrap(), &1.0);
assert_eq!(i.next().unwrap(), &1.5);
assert_eq!(i.next().unwrap(), &2.0);```

#### `fn iter_mut(&mut self) -> IterMut<T>`

Returns a mutable iterator over all elements of the matrix in row-major order.

```use rustml::*;

let mut m = mat![
1.0, 1.5;
2.0, 2.5
];
for i in m.iter_mut() {
*i = *i * 2.0;
}
assert!(m.eq(&mat![2.0, 3.0; 4.0, 5.0]));```

#### `fn row_iter(&self) -> RowIterator<T>`

Returns an iterator over the rows of the matrix.

Each call to the `next` method is done in O(1).

```use rustml::*;

let m = mat![
1.0, 1.5;
2.0, 2.5;
5.0, 5.5
];
let mut i = m.row_iter();
assert_eq!(i.next().unwrap(), [1.0, 1.5]);
assert_eq!(i.next().unwrap(), [2.0, 2.5]);
assert_eq!(i.next().unwrap(), [5.0, 5.5]);```

#### `fn row_iter_at(&self, n: usize) -> RowIterator<T>`

Returns an iterator over the rows of the matrix. The iterator starts at the the row with index `n`.

```use rustml::*;

let m = mat![
1.0, 1.5;
2.0, 2.5;
5.0, 5.5
];
let mut i = m.row_iter_at(1);
assert_eq!(i.next().unwrap(), [2.0, 2.5]);
assert_eq!(i.next().unwrap(), [5.0, 5.5]);```

#### `fn row_iter_of(&self, rows: &[usize]) -> SelectedRowIterator<T>`

Returns an iterator over the rows of the matrix with the specified indexes in `rows`.

```use rustml::*;

let m = mat![
1.0, 1.5;
2.0, 2.5;
3.0, 3.5;
4.0, 4.5;
5.0, 5.5
];
let mut i = m.row_iter_of(&[1, 3, 4]);
assert_eq!(i.next().unwrap(), [2.0, 2.5]);
assert_eq!(i.next().unwrap(), [4.0, 4.5]);
assert_eq!(i.next().unwrap(), [5.0, 5.5]);```

#### `fn get(&self, row: usize, col: usize) -> Option<&T>`

Returns the element of the matrix at row `row` (indexing starts at zero) and column `col` or `None` if row or column does not exist.

```use rustml::*;

let m = mat![
1.0, 1.5;
2.0, 2.5;
5.0, 5.5
];
assert_eq!(m.get(0, 1).unwrap(), &1.5);
assert_eq!(m.get(2, 0).unwrap(), &5.0);
assert!(m.get(3, 0).is_none());```

#### `fn row(&self, n: usize) -> Option<&[T]>`

Returns the row at index `n` (starting at zero) in O(1).

```use rustml::*;

let m = mat![
1.0, 1.5;
2.0, 2.5;
5.0, 5.5
];
assert_eq!(m.row(0).unwrap(), [1.0, 1.5]);
assert_eq!(m.row(1).unwrap(), [2.0, 2.5]);
assert_eq!(m.row(2).unwrap(), [5.0, 5.5]);
assert!(m.row(3).is_none())```

#### `fn row_mut(&mut self, n: usize) -> Option<&mut [T]>`

Returns the row at index `n` in O(1) that is mutable.

```use rustml::*;

let mut m = mat![
1.0, 1.5;
2.0, 2.5;
5.0, 5.5
];
{
let r = m.row_mut(1).unwrap();
r[0] = 4.0;
r[1] = 3.0;
}
assert_eq!(m.row(1).unwrap(), [4.0, 3.0]);```

#### `fn set(&mut self, row: usize, col: usize, newval: T) -> bool`

Replaces the element at row `row` (indexing starts at zero) and column `col` with the new value `newval`. Returns true on success and false on failure, i.e. if the row or column does not exist.

```use rustml::*;

let mut m = mat![
1.0, 1.5;
2.0, 2.5;
5.0, 5.5
];
assert_eq!(m.get(1, 0).unwrap(), &2.0);
m.set(1, 0, 8.0);
assert_eq!(m.get(1, 0).unwrap(), &8.0);
assert_eq!(m.set(3, 0, 8.9), false);```

#### `fn push_matrix_below(&self, m: &Matrix<T>) -> Option<Matrix<T>>`

Extends the current matrix by putting the matrix `m` below it.

#### `fn insert_column(&self, pos: usize, v: &[T]) -> Matrix<T>`

Inserts a column before the specified column (indexing starts at zero).

If the matrix is empty a new matrix `n x 1` matrix is returned where `n` is the number of elements in `v`. If `pos` is greater or equal to the number columns the vector is appended as a new column.

If the matrix is not empty and `v.len() != self.rows()` a `None` is returned.

#### `fn column(&self, pos: usize) -> Option<Vec<T>>`

Returns a copy of the column at the specified index.

#### `fn rm_column(&self, pos: usize) -> Matrix<T>`

Removes the column at index `pos` (indexing starts at zero) and returns the result.

Panics if the column does not exist.

#### `fn if_then_else<F>(&self, prd: F, tr: T, fa: T) -> Matrix<T> where F: Fn(&T) -> bool`

Iterates through the elements of the matrix, replaces elements and returns the new matrix.

A element is replaced by `tr` if the predicate `prd` evaluated for this element returns `true`. If the predicate returns `false` the element is replaced by `fa`.

The complexity is O(n) where `n` is the number of elements of the matrix.

#### `fn if_then_else_mut<F>(&mut self, prd: F, tr: T, fa: T) where F: Fn(&T) -> bool`

Iterates through the elements of the matrix and replaces the elements inplace.

A element is replaced by `tr` if the predicate `prd` evaluated for this element returns `true`. If the predicate returns `false` the element is replaced by `fa`.

The complexity is O(n) where `n` is the number of elements of the matrix.

#### `fn reshape_mut(&mut self, rows: usize, cols: usize)`

Reshapes the matrix, i.e. modifies the number of rows and columns.

The complexity of this function is O(1) if `rows * cols` is equal to the number of elements in the matrix. If the new number of elements is smaller than the current number of elements the complexity is equal to the complexity of `Vec::truncate`.

Panics if `rows * cols` is greater than the number of elements stored in the matrix.

#### `fn reshape(&self, rows: usize, cols: usize) -> Matrix<T>`

Reshapes the matrix, i.e. modifies the number of rows and columns and returns the result.

The complexity of this function is O(rows * cols).

Panics if `rows * cols` is greater than the number of elements stored in the matrix.