subarray(X, range)


X is a vector/matrix.

range is a pair of integers indicating a range. The lower bound is inclusive and the upper bound is exclusive.


When a subset of the elements of a vector are needed in calculation, if we use script such as close[10:].avg(), a new vector close[10:] is generated with replicated data from the original vector close before the calculation is conducted. This not only consumes more memory but also takes time.

Function subarray generates a subarray of the original vector. It only records the pointer to the original vector together with the starting and ending positions of the subarray. As the system does not allocate a large block of memory to store the subarray, data replication does not occur. All read-only operations on vectors can be applied directly to a subarray.


Example 1

subarray(x, 10:20);
// output

subarray(x, 90:);
// output

subarray(x, :10);
// output

Example 2

timer a.subarray(0:1000000).avg();
// output
Time elapsed: 2.037 ms

timer a[0:1000000].avg();
// output
Time elapsed: 36.583 ms

Example 3. Subarrays are read-only.

// output
Immutable sub vector doesn't support method set