Indexing in ArrayFire is a powerful but easy to abuse feature. This feature allows you to reference or copy subsections of a larger array and perform operations on only a subset of elements.
This chapter is split into the following sections:
- Index an Array using Seq Objects
- Using Array and Seq combination
- Extract or Set rows/columns of an Array
- Negative Indices
Indexer structure is the key element used in Rust wrapper of ArrayFire for creating references
to existing Arrays. The above sections illustrate how it can be used in conjunction with Seq
and/or Array
. Apart from that, each section also showcases a macro based equivalent
code(if one exists) that is more terse in syntax but offers the same functionality.
We will Sequences and the function index in this approach.
{{#include ../../src/core/index.rs:non_macro_seq_index}}
However, the same above code can be condensed into a much terse syntax with the help of view macro. Take a look at the following two approaches using view macro.
{{#include ../../src/core/index.rs:seq_index}}
{{#include ../../src/core/macros.rs:seq_view2}}
Let us take a look at an example where a portion of an existing Array will be set to with another Array. We will an constant value Array and the function assign_seq in the below example.
{{#include ../../src/core/index.rs:non_macro_seq_assign}}
A much terser way of doing the same using macro is shown below
{{#include ../../src/core/macros.rs:macro_seq_assign}}
NOTE Normally you want to avoid accessing individual elements of the array like this for performance reasons.
To use a combination of Array and Seq objects to index an existing Array, we will need a more generalized function index_gen.
{{#include ../../src/core/index.rs:non_macro_seq_array_index}}
Similar to how view macro helped with abreviating the syntax when indexing with just sequences, it can also help when using a combination of Seq and Array.
{{#include ../../src/core/index.rs:seq_array_index}}
Set a portion of an existing Array with another Array using a combination of Seq
and Array
.
We will use assign_gen function to do it.
{{#include ../../src/core/index.rs:non_macro_seq_array_assign}}
{{#include ../../src/core/macros.rs:macro_seq_array_assign}}
Extract a specific set of rows/coloumns from an existing Array.
{{#include ../../src/core/index.rs:setrow}}
You can also use rows & cols to retrieve a subset of rows or coloumns respectively.
Similarly, set_row & set_rows can be used to change the values in a particular set of rows using another Array. set_col & set_cols has same functionality, except that it is for coloumns.
Negative indices can also be used to refer elements from the end of a given axis. Negative value for a row/column/slice will fetch corresponding row/column/slice in reverse order. Given below are some examples that showcase getting row(s)/col(s) from an existing Array.
{{#include ../../src/core/index.rs:get_row}}
{{#include ../../src/core/index.rs:get_rows}}