Vectors
A VECTOR is another complex Explain™ data type. It is analogous to the arrays that are common in other computer languages. Like an array, a VECTOR contains a number of elements that are accessed by a numerical index into the VECTOR. Unlike traditional arrays, an Explain VECTOR can contain a mixture of data types including both simple data types and objects.
The only information needed to create a new VECTOR is the number of elements that are required. The data type of the VECTOR elements is not specified when the VECTOR is created. For example, this statement creates a new six-element VECTOR named XVector.
XVector = VectorNew(6)
The elements of the new VECTOR are all initialized to the NIL data type.
The index of a VECTOR (which are the INDEX data type) to access elements of the VECTOR starts with zero.
The six elements of the XVector are therefore numbered 0 to 5. To access a VECTOR element, you give the VECTOR name followed by the index in square brackets. For example, to assign the REAL value 5.0 to the third element of your XVector, you can use the line:
XVector[2] = 5.0 ; third element becomes a REAL with value of 5.0
Notice that the NthVECTOR element has an index of N – 1 because a VECTOR’s index starts with zero.
You can assign the contents of the VECTOR element to a regular Explain variable (in this example called Variable2) as follows:
Variable2 = XVector[2] ; Variable2 becomes a REAL with value of 5.0
The index into aVECTOR often may be a loop counter. For example, this code fragment stores the square of the integers 0 to 9 in the elements of a VECTOR called Squares:
Squares = VectorNew(10)
i = 0
while ( i lt 10)
Squares[i] = i * i
i = i + 1
… ; next statement after the loop
Similar to Explain variables, the elements take the data type of data that is assigned to them. This line reassigns the third element of XVector to an object of the CPIV curve class.
XVector[2] = CPIV.New(…) ; New() function arguments left out for clarity
You can still access all the CPIV object’s functions. For example, objects of the CPIV class have an instance function Printl() that prints the curve to the output file. To call this function using the CPIV object in XVector use this line:
XVector[2].Printl()
A VECTOR element can contain another VECTOR. You can therefore generate a construct similar to a two-dimensional array:
XYVector = VectorNew(5)
i = 0
while(i lt 5)
XYVector[i] = VectorNew(10)
i = i +1
… ; next statement after the loop
This code generates a two-dimensional VECTOR with five columns and ten rows. To access the Nth element in row M, the syntax is XYVector[N-1] [M-1]. Remember that VECTOR indexes start at zero.
Comments are closed.