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

$ x=1..100
$ subarray(x, 10:20);

$ subarray(x, 90:);

$ subarray(x, :10);

Example 2

$ a=rand(1000.0,20000000);
$ timer a.subarray(0:1000000).avg();
Time elapsed: 2.037 ms

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

Example 3. Subarrays are read-only.

$ b=a.subarray(0:1000000);
$ b[0]=1;
Immutable sub vector doesn't support method set