indexing
An index is a way to access elements of a data structure, such as arrays, matrices, or tables, using specific criteria or positions.
Introduction
There are various ways to access elements within data structures in Mech. The most common methods are:
Regular Indexing - Accessing elements using specific integer positions.
Matrix Slicing - Accessing multiple elements at once using ranges or entire rows/columns.
Logical Indexing - Accessing elements based on boolean conditions.
Dot Indexing - Accessing fields or properties of structured data types.
Matrix Slicing
Slicing allows you to access multiple elements at once, either entire rows or columns, or specific ranges of rows and columns.
The : operator can be used to access entire rows or columns:
You can slice it in various ways. For a matrix x with N rows and M columns, the following indexing operations are valid:
Syntax | Description | Resulting Size |
|---|---|---|
x[:] | Slice all elements |
|
x[1,:] | Slice a row |
|
x[:,2] | Slice a column |
|
x[1..=2,:] | Slice a range of rows |
|
| Slice specific rows |
|
| Slice specific rows and columns |
|
| Slice the rows multiple times |
|
For more, see the matrix documentation.
Logical Indexing
A logical index is a boolean array (true / false) of the same size
as the data being indexed. Elements corresponding to true are selected; those
corresponding to false are ignored.
Expression | Description | Result |
|---|---|---|
| All positive elements |
|
| All negative elements |
|
| All zero elements |
|
| All non-zero elements |
|
Logical indexing can also be applied per row or per column by using logical
vectors.
Syntax | Description | Resulting Size |
|---|---|---|
| Select rows where |
|
| Select columns where |
|
| Select rows and columns logically |
|
You can combine logical conditions using logical operators:
This selects [1, 3], the elements greater than 0 and less than 4.
Logical indexing can be combined with regular indexing for more complex selections. For example, to select positive elements from the first two rows:
Dot Indexing
Dot indexing is used to access fields or properties of structured data types, such as records or objects.
To access the fields of the person record, you can use dot notation:
Expression | Description | Result |
|---|---|---|
| Access the |
|
| Access the |
|
| Access the |
|
Dot indexing can also be used with tables:
name<string> | age<u8> | position<string> |
|---|---|---|
| "Bob" | 28 | "Engineer" |
| "Carol" | 34 | "Manager" |
| "Dave" | 25 | "Intern" |
| "Eve" | 30 | "Designer" |
You can use dot indexing to access columns in the table:
This returns the name column: ["Bob", "Carol", "Dave", "Eve"].