Skip to content

Range-based indexing #149

@Andlon

Description

@Andlon

Currently, to take a slice of a matrix, one needs to use e.g. the sub_slice function. I propose to add implementations of Index<(Range<usize>, Range<usize>)>. See the following example:

let x = matrix![ 1.0, 2.0, 3.0;
                 4.0, 5.0, 6.0;
                 7.0, 8.0, 9.0];

// Want to take the 2x2 lower-right corner
// Current way:
let corner = x.sub_slice([1, 1], 2, 2);

// Range-based indexing:
let corner = x[(1 .. 3, 1 .. 3)];

// Or, more succinctly:
let corner = x[(1 .., 1 ..)];

// More flexible indexing, let's take the two first columns
let two_last_cols = x[( .. 2, ..)]

Similarly, we can slice rows or columns (returning Row or Column) using a mix of usize and Range<usize>:

let second_row = x[(1, ..)];
let second_col = x[(.., 1)];

// Only parts of a given row, still returns a `Row` struct 
// (so we can extract a raw slice, which is useful for performance)
let parts_of_second_row = x[(1, 1 .. 3 )];

The range-based indexing can be implemented in terms of Index<(R1, R2)> where R1, R2 are any of the following concrete types from the stdlib: Range, RangeFull, RangeTo, RangeFrom.

Any thoughts on this? I think it would really empower matrix slices.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions