6.5 Vectors and matrices

Vectors are similar to lists, except that all of their elements must be real numbers, and that all of the elements of any given vector must share common physical dimensions. Vectors are stored much more efficiently in memory than lists, since information about the types and physical units of each of the elements need not be stored. In addition they support a wide range of vector and matrix arithmetic operations.

For example, applying the addition + operator to two lists concatenates the lists together, meanwhile the same operator applied to two vectors performs vector addition:

In fact, whilst vectors do support the same append and extend methods as lists, to add either a single new element, or a list of new elements, to the end of the vector, these are very time consuming methods to run. It is much more efficient to create a vector of the desired length, and then to populate it with elements:

As the above example demonstrates, the vector() prototype can take not only a list or vector from which to make a vector object copy, but alternatively a single integer, which creates a zeroed vector of the specified length.

Similarly, the matrix() prototype can create a matrix from a list of lists, a list of vectors, a series of list arguments, a series of vector arguments, or two integers. In the final case, a zero matrix with the specified number of rows and columns is returned. If a matrix is specified as a series of vectors, these are taken to be the columns of the matrix; but if the matrix is specified as a series of lists, these are taken to be the rows of the matrix: