How do you index select/copy from a Matrix in Rust


#1

I have a matrix that looks like this:

pub struct Matrix<T> {
    pub grid: Vec<T>,
}

/// constructor
impl<T> Matrix<T> {
    pub fn new(data: Vec<T>) -> Matrix<T> {
        Matrix { grid: data }
    }
}

I need to be able to do something like this, something close to the iloc of Python’s pandas if you know what that is (Pandas Cheat sheet):

// m equals a matrix of type Vec<String>
// the matrix is 11 rows 4 columns. I dont want the first row
// because of headers or the first or last column.
// args {cols: Vec<?>||tuple(i64,str,i64), rows: Vec<?>||tuple(i64,str,i64}
let data = m.extract(vec![1,2], (-1,':',))

I have looked at those other libraries and they are great for what they do but I am working on something that these libraries do not accomplish.

The arguments for the extraction is columns, rows, which I would like to take either a tuple or Vec, but if that is not possible I will settle for a vector. As stated this syntax is derived from python’s pandas library which I posted a link to the cheat sheet with reference to the iloc function. So vec![1,2] would return me only columns 1 and 2 with index starting at 0. While for the tuple (-1,':',), I would want to return all rows except the first. So if instead it was (,':',-1) I would get all the rows except the last. (1,':',6) would return rows 1-6 including all in between. (,':',) would return all rows. Which (0,':',0) and vec![0] both give only the first row/column except the vector type cannot specify a range.

As for the data structure I want to return is a Matrix like the ones used in the other matrix libraries. A matrix type with rows, columns and data. I am reading in a csv file into a generic Matrix T which I should probably turn into just a String since I doubt I will ever change that. I need to be able to convert the data int the String matrix into f64 and then have a new matrix type hold that to work matrices math on. I still need to keep the String matrix as a reference to create my own logic to communicate positive or negative feedback(true/false) on fields that contain things like country names by a match or with yes/no in columns.

How would I iterate over this matrix which will contain a Vec<Vec<T>> to retrieve a specific matrix from it? I have headers, and I want all the data so I need to skip the index of Matrix.grid[0] but none else.

Do I need to write an impl Iterator and if so how would this be done? I have seen an example with a different format but do I need lifetimes to accomplish this? Is there anything I need to add the the struct or with a impl to get the capability to copy, get a mut ref to all values, a ref to all values?

I am rather new to Rust and am very eager to learn more. I have read the whole Rust book, taken a course online, but still I find myself lost when dealing with a Matrix.