One of the powerful features of HTBasic is its ability to do operations on complete arrays without the use of loops. This means that programs will run much faster. Many operators that can operate on two simple variables can operate on arrays. Array/array operations or array/scalar (simple variable) operations can be done. Portions or entire arrays can be transferred to another array or a portion of another array. For example:
DIM X(10),Y(10),Z(10)
MAT Y=(1) ! defines every element of the array
MAT X=Y*(5) ! array/scalar operation
MAT Z=X+Y ! array/array operation
MAT Z(2:3)=Z(9:10) ! sub-array assignment
The operators + - . / < <= = >= > <> require that the operand arrays have the same RANK and that each dimension has the same SIZE. The result array will be REDIMed if needed. However, the usual rules for REDIM apply and if the array cannot be redimensioned, an error is returned. Each of these operators work on the array element by element. The "." operator does an element by element multiply.
The * operator performs classical matrix multiplication. The definition of matrix multiplication is given in the following BASIC SUB:
SUB Matmpy(A(*),B(*),C(*)) ! Equivalent to MAT C=A*B
OPTION BASE 1
INTEGER I,J,K,M,N,R
M=SIZE(A,1)
N=SIZE(A,2)
K=SIZE(B,2)
IF N<>SIZE(B,1) THEN CAUSE ERROR 16
REDIM C(M,K)
FOR I=1 TO M
FOR J=1 TO K
Sum=0
FOR R=1 TO N
Sum=Sum+A(I,R)*B(R,J)
NEXT R
C(I,J)=Sum
NEXT J
NEXT I
SUBEND
Matrix Operators with Matrix Result
Operator
|
Functionality
|
CSUM
|
Returns the sum of each column of a 2D array in a vector
|
IDN
|
The identity matrix (1’s along diagonal, 0’s elsewhere)
|
INV
|
Sets one array to the inverse of another
|
REORDER
|
Reorders the elements of an array
|
RSUM
|
Returns the sum up each row of a 2D array in a vector
|
SEARCH
|
Searches for elements in an array
|
SORT
|
Sorts arrays in ascending or descending order
|
TRN
|
Transposes a matrix (rows to columns, columns to rows)
|
Matrix Operators with Scalar Result
Operator
|
Functionality
|
BASE
|
Returns the lowest legal subscript for a dimension
|
DET
|
Returns the determinant of a matrix
|
DOT
|
Dot, or inner product of two vectors
|
MAX
|
Returns largest element of an array and/or scalars
|
MIN
|
Returns smallest element of an array and/or scalars
|
RANK
|
Number of dimensions in a matrix
|
SIZE
|
Upper bound - lower bound + 1 of a dimension
|
SUM
|
Adds up all the elements in an array
|
Sub-array assignments (sometimes called array slices) require that the number of ranges specified in the source match the number of ranges specified in the destination. If a complete array is specified, the number of ranges equals the rank of the array. In corresponding ranges of the source and destination, the number of elements must be the same. The following examples will help you visualize these rules:
DIM X(1:3),Y(1:10)
DIM D(3,4,5),S(4,2,5)
MAT X=Y(2:4) ! One range, three elements
MAT D(3,*,*)=S(*,2,*) ! Range 1 has 5 elements, 2 has 6
MAT Y(1:6)=S(0,0,*) ! One range, 6 elements