rust_basic_matrix/
lib.rs

1use std::vec::Vec;
2
3pub struct Matrix<T> {
4	data: Vec<T>,
5	pub cols: usize,
6	pub rows: usize
7}
8
9impl<T: Clone> Matrix<T> {
10
11	pub fn new(rows: usize, cols: usize, initial: T) -> Matrix<T> {
12		let data = (0..rows*cols).map(|_| initial.clone()).collect();
13		
14		Matrix {
15			cols: cols,
16			rows: rows,
17			data: data
18		}
19	}
20
21	pub fn with_data(rows: usize, cols: usize, initial: T, old_data: &Vec<T>, data_rows: usize, data_cols: usize) -> Matrix<T> {
22		let mut data: Vec<T> = (0..rows * cols).map(|_| initial.clone()).collect();
23
24		for row in 0..data_rows {
25			for col in 0..data_cols {
26				data[(row * cols) + col] = old_data[(row * data_cols) + col].clone();
27			}
28		}
29
30		return Matrix {
31			data: data,
32			rows: rows,
33			cols: cols
34		}
35	}
36
37	pub fn get(&self, row: usize, col: usize) -> T {
38		self.data[(row * self.cols) + col].clone()
39	}
40
41	pub fn set(&mut self, row: usize, col: usize, val: T) {
42		self.data[(row * self.cols) + col] = val;
43	}
44
45	/**
46	 * Expand or contract the matrix, filling any new slots with initial
47	 */
48	pub fn resize(&self, new_rows: usize, new_cols: usize, initial: T) -> Matrix<T> {
49		Matrix::with_data(new_rows, new_cols, initial, &self.data, self.rows, self.cols)
50	}
51}