cart_lin
A library for converting between linear and cartesian indices.
This library offers the following functions for conversion between linear and cartesian indices for any number of dimensions:
cart_to_linandcart_to_lin_unchecked: Convert a cartesian index (e.g.[1, 2, 5]for a three-dimensional matrix) into a linear index (i.e. the position in the underlying contiguous memory).lin_to_cartandlin_to_cart_unchecked: Convert a linear index into a cartesian index.lin_to_cart_dynandlin_to_cart_dyn_unchecked: These variations oflin_to_cartwrite the calculated cartesian indices into a caller-provided slice buffer instead of returning an index array.
Additionally, CartesianIndices provides an iterator over cartesian indices which can be seen
as the multidimensional equivalent of the Range(https://doc.rust-lang.org/std/ops/struct.Range.html) iterator.
Cartesian to linear index conversion
Let's use the following 2x3 matrix (two rows, three columns) as an example:
The cartesian index of element 0 is [0, 0], that of 1 is [0, 1], that of 5 is [1, 2] and so on.
cart_to_lin (as well as all other functions of this library) uses row-major order
(= last index changes fastest).
use cart_to_lin;
// Rows, columns
let dim_size = ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
For higher-dimensional matrices, it works in the same way (using the example of a matrix with 4 rows, 3 columns and 2 pages):
use cart_to_lin;
// Rows, columns, pages
let dim_size = ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
cart_to_lin checks whether the given cartesian index is valid for the specified number of dimensions.
In order to avoid this check, use cart_to_lin_unchecked (which is not unsafe, but might return
invalid indices).
Linear to cartesian conversion
The inverse of cart_to_lin is lin_to_cart:
use lin_to_cart;
// Rows, columns
let dim_size = ;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
Iterate over cartesian indices
use CartesianIndices;
let mut cartiter = new;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
CartesianIndices can also be constructed by defining lower and upper bounds for each axis.
The following example is functionally equivalent to the previous one:
use CartesianIndices;
let mut cartiter = from_bounds.expect;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
But it is also possible to add offsets via the lower bounds:
use CartesianIndices;
let mut cartiter = from_bounds.expect;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;