LOOP Function

You are here:
< All Topics

LOOP(Vector1, Vector2, Offset1, Offset2, Operator) 

LOOP provides simulated control structure by means of a single function call. Consider the following: 


SET X = REF(X, 1) + X 

This script simply ads the previous close to the most current close. 

REF(X, 1) is evaluated once. This is expected behavior for a vector programming language; vectors are calculated independently in a stepwise fashion and are not recursive. 

Now by changing CLOSE to 0, logically we would expect X to equal the previous X value plus one, and therefore expect REF(X, 1) to be evaluated once for each record in the vector: 

SET X = 0 

SET X = REF(X, 1) + X 

Although we are looking at the exact same formula, because we are initializing X with a scalar and X is not related to any existing vector we would now expect X to be calculated as a series: 1,2,3,4,5,6,…n 

We are now exceeding the limits of a vector programming language by requiring control structure.

Anytime we assign a variable to itself such as SET X = F(X) we are expecting F(X) to be recursive. In the first example we write SET X = CLOSE. CLOSE is a variable, not a function and does not have any relationship with X . Our expectations change when we initialize X with anything other than an existing vector. 

The LOOP function overcomes this inherent limitation by simulating a structured programming construct, the for-loop iteration: 

LOOP(Vector1, Vector2, Offset1, Offset2, Operator) 

Vector1 is the vector to initialize the calculation from. Offset1 is the offset where values are referenced in Vector1 for the incremental calculation, and Offset2 is the offset where values are referenced from in Vector2

Example 1: 

X (Vector1 ) is a series from 5.25 to 11.25. If we write LOOP(X, 2, 1, 0, MULTIPLY) the vector returned will contain values initialized by X, offset by 1 and multiplied by 2

Example 2: 

In the case of SET X = REF(X, 1) , Vector1 is X and Vector2 is 1. Since we’re adding the value of 1 (not a vector) to X in the following example, Offset2 is set to zero: 

SET X = LOOP(X, 1, 1, 0, ADD) 

And now X contains the series 1,2,3,4,5,6,…n 

Example 3: 


SET Y = (REF(Y, 3) – X) * 2 

Because Y requires control structure we must instead write: 


SET Y = LOOP(Y, X, 3, 0, SUBTRACT) * 2 

We could reduce that to: 


Valid operators are ADD , SUBTRACT, MULTIPLY and DIVIDE.

Table of Contents