subarray
Syntax
subarray(X, range)
Arguments
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.
Details
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.
Examples
Example 1
x=1..100
subarray(x, 10:20);
// output
[11,12,13,14,15,16,17,18,19,20]
subarray(x, 90:);
// output
[91,92,93,94,95,96,97,98,99,100]
subarray(x, :10);
// output
[1,2,3,4,5,6,7,8,9,10]
Example 2
a=rand(1000.0,20000000);
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.
b=a.subarray(0:1000000);
b[0]=1;
// output
Immutable sub vector doesn't support method set