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:

pyxplot> a = [1,2,3]
pyxplot> b = [4,0,6]
pyxplot> print a+b
[1, 2, 3, 4, 0, 6]
pyxplot> av = vector(a)
pyxplot> bv = vector(b)
pyxplot> print av+bv
vector(5, 2, 9)

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:

pyxplot> a = vector(10)*unit(m)
pyxplot> print a
vector(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)*unit(m)
pyxplot> a[5] = unit(inch)
pyxplot> print a
vector(0, 0, 0, 0, 0, 0.0254, 0, 0, 0, 0)*unit(m)

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:

pyxplot> print matrix(3,4)
(0, 0, 0, 0)
(0, 0, 0, 0)
(0, 0, 0, 0)
pyxplot> print matrix([[1,2],[3,4]])
(1, 2)
(3, 4)
pyxplot> print matrix([vector(1,2),vector(3,4)])
(1, 3)
(2, 4)

Like vectors, matrices can have physical units, and adding two matrices together performs element-wise addition:

pyxplot> a = matrix([1,0],[0,1])*unit(s)
pyxplot> b = matrix([0,-1],[-1,0])*unit(s)
pyxplot> print a+b
(1, -1)
(-1, 1) *unit(s)