5 Points, vectors, and containers
This section discusses the mathematical objects points and vectors and then their representation using different container types from Julia. It ends with a discussion of the basics of some fundamental container types.
5.1 Points
A point in two-dimensional space is typically represented in the Cartesian plane through a pair of coordinates \((x,y)\). The origin is the point \((0,0)\). Common mathematical notation is to use parentheses to group the two coordinates with the order on the axes to be understood (\(x\) is first, \(y\) is second). If a point is labeled, it is typical to use a capital letter. For a point in 3-dimensions, the notation just adds a coordinate to get \((x,y,z)\) representing a generic point and \((0,0,0)\) the origin. A generalization to \(n\)-dimensions might use the notation \((x_1, x_2, \dots, x_n)\) to represent a point. Some books might refer to this as an \(n\)-tuple.
The coordinates represent a position along an axis. For example, the point \((4,5)\) being \(4\) units along the \(x\) axis and \(5\) units up the \(y\) axis.
For the \(1\) dimensional case, the point is just a number on the number line. Typically a point is written as a number; there isn’t a common convention to write as a \(1\)-tuple, in the sense above.
A typical question about points is how far apart are two different points. For \(2\)-dimensional points \(P = (x_1, y_1)\) and \(Q = (x_2, y_2)\) we can use the distance formula:
\[ d = \overline{PQ} = \sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2}. \]
This formula agrees with Pythagorean’s theorem for right triangles.
For \(n\)-dimensional points, the same formula may be used with adjustments to the notation. Suppose \(P = (x_1, x_2, \dots, x_n)\) and \(Q = (y_1, y_2, \cdots, y_n)\). then
\[ d = \overline{PQ} = \sqrt{(x_1 - y_1)^2 + (x_2 - y_2)^2 + \cdots + (x_n - y_n)^2}. \]
(Note the difference in how the point is described—in two dimensions we use variations of \((x,y)\), in \(n\)-dimensions just a single subscripted name for the components of a point.
It is well known that two distinct points determine a line in the Cartesian plane, a fact that extends to \(n\)-dimensional space. Two points also define a line segment, that part of the line bounded by the two endpoints.
5.2 Vectors
We now discuss a related but not identical mathematical object, a vector.
As mentioned, a line segment is the portion of a line between two points. A line segment can be given a direction by assigning an initial point and a terminal point. A directed line segment has both a direction and a magnitude. A vector is an abstraction where just these two properties—a direction and a magnitude—are intrinsic.
While a directed line segment can be represented by a vector, a single vector describes all such line segments found by translation. That is, how the vector is located when visualized is for convenience, it is not a characteristic of the vector.
A two-dimensional vector has two components, as does a point in the Cartesian plane. To distinguish a vector from a point a different mathematical notation is used. The vector components are combined with angle brackets and any name traditionally has an arrow mark above it: \(\vec{v} = \langle x,~ y \rangle\)1.
Suppose a vector is defined as being between two points \(P = (x_1, y_1)\) and \(Q = (x_2, y_2)\) with \(P\) the endpoint, then the vector connecting \(P\) to \(Q\) would be \(\vec{v} = \langle x_2 - x_1, ~ y_2 - y_1 \rangle\).
When \(P = (0,0)\), the the point \(Q = (x_2, y_2)\) has the same components as the vector \(\vec{v} = \langle x_2, ~ y_2 \rangle\) leading to a natural identification between a point and vector, though they represent different things.
5.2.1 Basic properties
The magnitude of a vector is the length of the line segment between the tip and tail and is given by the distance formula.
\[ \lVert \vec{v} \rVert = \lVert \langle x, ~ y\rangle \rVert = \sqrt{x^2 + y^2} \]
The notation \(\lVert \vec{v} \rVert\) is called the norm of the vector. A vector with magnitude \(1\) is called a unit vector.
There are two fundamental vector operations.
Vectors can be multiplied by a scalar: \(c\vec{v} = \langle cx,~ cy \rangle\). A scalar is a number and scalar multiplication multiplies each component of a vector by that scalar to produce a scaled vector. For \(c > 0\) scalar multiplication does not change the direction. If \(c < 0\) then the direction is flipped opposite.
Vectors can be added component by component: \(\vec{v} + \vec{w} = \langle v_x + w_x,~ v_y + w_y \rangle\). That is, each corresponding component adds to form a new vector. The \(\vec{0}\) vector then would be just \(\langle 0,~ 0 \rangle\) and would satisfy \(\vec{0} + \vec{v} = \vec{v}\) for any vector \(\vec{v}\).
Vector subtraction \(\vec{v} - \vec{w}\) can be defined by \(\vec{v} + (-\vec{w})\) and can be computed component by component. Subtraction can be visualized by drawing a vector of the same magnitude, but opposite direction of \(\vec{w}\), anchored at the tip of \(\vec{v}\).
Scalar division is just scalar multiplication written through \(\vec{v}/c\) (with the scalar last). There is no definition of a scalar divided by a vector. Scalar multiplication can also be written first or last for commutative number types.
A general expression of the type \(a\vec{v} + b\vec{w}\) for scalars \(a\) and \(b\) is called a linear combination of the vectors \(\vec{v}\) and \(\vec{w}\).
For any non-zero vector, \(\vec{v}\), the norm is the length of the vector and the scaled vector \(\hat{v} = \vec{v} / \lVert\vec{v}\rVert\) is a unit vector in the direction of \(\vec{v}\). Writing \(\vec{v} = \lVert \vec{v} \rVert \hat{v}\) decomposes \(\vec{v}\) into a length and a direction.
Visualization
In the Cartesian plane, we can visualize a vector by fixing a point and then drawing the corresponding arrow with the point as the end point. However vectors can be anchored anywhere in the plane so this fixed point should be chosen to illustrate some feature.
We illustrate scalar multiplication and scalar addition in Figure 5.1.
5.2.2 Example: motion
One of the first models learned in physics are the equations governing the laws of motion with constant acceleration: \(x(t) = x_0 + v_0 t + 1/2 \cdot a \cdot t^2\). This is a consequence of Newton’s second law of motion applied to the constant acceleration case. A related formula for the velocity is \(v(t) = v_0 + a\cdot t\). The following figure is produced using these formulas applied to both the vertical position and the horizontal position of some projectile.
For the motion in Figure 5.2, the object’s \(x\) and \(y\) values change according to the same rule, but, as the acceleration is different in each direction, we get different formula, namely: \(x(t) = x_0 + v_{0x} t\) and \(y(t) = y_0 + v_{0y}t - 1/2 \cdot gt^2\). The acceleration is \(0\) in the \(x\) direction and \(-g\) in the \(y\) direction (all due to gravity).
It is common to work with both formulas at once. The following uses vectors to define the position, velocity, and acceleration dependent on \(t\):
\[ \begin{align*} \vec{x} &= \langle x_0 + v_{0x}t,~ -(1/2) g t^2 + v_{0y}t + y_0 \rangle,\\ \vec{v} &= \langle v_{0x},~ -gt + v_{0y} \rangle, \text{ and }\\ \vec{a} &= \langle 0,~ -g \rangle. \end{align*} \]
Don’t spend time thinking about the formulas if they are unfamiliar. The point emphasized here is that we have used vector notation to collect the two values into a single object.
Figure 5.2 shows the position vector, \(\vec{x}\), anchored at the origin and the velocity and acceleration vectors, \(\vec{v}\) and \(\vec{a}\), anchored at the position. The acceleration is a constant, pointing downwards; the velocity tracking the direction of the motion.
Now, let’s breakdown \(\vec{x}\). It comes from two components each of the form \(x_0 + v_0\cdot t -(1/2) a \cdot t^2\). If we define the initial position, initial velocity, and constant acceleration into vectors we have:
\[ \begin{align*} \vec{x}_0 &= \langle x_0 ,~ y_0 \rangle,\\ \vec{v}_0 &= \langle v_{0x},~ v_{0y} \rangle, \text{ and }\\ \vec{a} &= \langle 0,~ -g \rangle. \end{align*} \]
With this, the vector \(\vec{x}\) can be written in a way using scalar multiplication and vector addition that exactly mirrors where each component comes from:
\[ \vec{x} = \vec{x}_0 + \vec{v}_0 \cdot t + (1/2) \vec{a} \cdot t^2, \]
This shows one reason why vectors (and generalizations) are so useful, they can unify multiple components into a single equation.
5.2.3 Higher dimensional vectors
Vectors, like points, are not limited to \(2\)- or \(3\)-dimensional space. A vector in an \(n\)-dimensional space has \(n\) components, say \(\vec{x} = \langle x_1, x_2, \dots, x_n \rangle\).
For such vectors, scalar multiplication and vector addition are defined in the same component-by-component manner.
The norm is similar, but to simplify notation we introduce the dot product between two \(n\)-dimensional vectors.
Let \(\vec{x} = \langle x_1, x_2, \dots, x_n \rangle\) and \(\vec{y} = \langle y_1, y_2, \dots, y_n \rangle\) then define the dot product of \(\vec{x}\) and \(\vec{y}\) by
\[ \vec{x} \cdot \vec{y} = x_1y_1 + x_2 y_2 + \cdots x_n y_n \]
It is clear from commutivity of multiplication that \(\vec{x} \cdot \vec{y} = \vec{y} \cdot \vec{x}\).
With this, we can define the magnitude of an \(n\)-dimensional vector through:
\[ \lVert \vec{x} \rVert = \sqrt{\vec{x} \cdot \vec{x}} \]
5.3 Containers
Julia has multiple data structures available. In this discussion we focus on a few foundational containers used to hold different collections.
5.3.1 Vector
A vector in Julia is a container in Julia for holding an arbitrary number of objects of the same type. These are used to represent a vector with \(n\) components. Vectors can be constructed with square brackets, [], as follows:
v = [1, 2, 3] # 𝐯 = ⟨1, 2, 3⟩3-element Vector{Int64}:
1
2
3
As can be read, this is a three element Vector of integer values. The standard display of a vector includes the length and the type. The square brackets in this case are used for array concatenation; they also have other meanings in the language, as we will soon see.
Vectors have scalar multiplication and vector addition supported:
w = [3, 2, 1]
2*v, v + w([2, 4, 6], [4, 4, 4])
The dot product and the norm functionality are found in the standard library LinearAlgebra. This must be loaded in order to be used:
using LinearAlgebraOnce loaded, we can access these features as follows:
dot(v, w), norm(v), sqrt(dot(v,v))(10, 3.7416573867739413, 3.7416573867739413)
In Julia there are many uses for vectors outside of physics applications. A vector in Julia is just a one-dimensional collection of similarly typed values and a special case of an array. Such objects find widespread usage. For example:
- In plotting graphs with
Julia, vectors are used to hold the \(x\) and \(y\) coordinates of a collection of points to plot and connect with straight lines. There can be hundreds of such points in a plot. - Vectors are a natural container to hold the coefficients of a polynomial.
- Vectors are a natural container to hold the roots of a polynomial, or the zeros of a function.
- Vectors may be used to record the state of an iterative process.
- Vectors are naturally used to represent a data set, such as arise when collecting survey data.
As mentioned, vectors in Julia are comprised of elements of a similar type, but the type is not limited to just numeric types. Some examples:
a vector of strings might be useful for text processing, For example, the
WordTokenizers.jlpackage takes text and produces tokens from the words.a vector of Boolean values can naturally arise and is widely used within Julia’s
DataFrames.jlpackage.some data is naturally represented in terms of vectors of vectors. For example, GPS tracks might use a vector to record sampled positions, each of which is a vector holding latitude and longitude readings.
Look at the output of these two vectors, in particular how the underlying type of the components is described on printing.
["one", "two", "three"] # T is String3-element Vector{String}:
"one"
"two"
"three"
[true, false, true] # T is Bool for Boolean values3-element Vector{Bool}:
1
0
1
Finally, we mention that if Julia has values of different types when put into a vector, they will be promoted to a common type, as possible. Here we combine three types of numbers, and see that each is promoted to Float64:
[1, 2.0, 3//1]3-element Vector{Float64}:
1.0
2.0
3.0
Whereas, in this example where there is no common type to promote the values to, a catch-all type of Any is used to hold the components.
["one", 2, 3.0, 4//1]4-element Vector{Any}:
"one"
2
3.0
4//1
5.3.2 AbstractArray
In Julia a Vector is of a more general type AbstractVector which itself is a specialization of the AbstractArray type. Abstract arrays are containers with multiple dimensions (N) filled with values of a certain type (T). Vectors are \(1\)-dimensional arrays; we will later see matrices which are \(2\) dimensional arrays. The language can be confusing. We have a vector with \(n\) components sits in an \(n\) dimensional space (a vector space) but it is represented with a \(1\) dimensional array with \(n\) components. The array dimension allows additional access patterns than are described in the following.
5.3.3 Tuple
A tuple is another container for holding a collection of \(n\) elements. Tuples are formed by separating values by commas; typically enclosed with parentheses. For example
P = (1, 2, 3)(1, 2, 3)
Tuples can hold values of different types2:
Q = (true, 1, pi)(true, 1, π)
A \(1\) element tuple is constructed with a comma as follows:
R = (1, )(1,)
A \(0\)-element tuple is constructed with `()$.
Tuples as a container do not support scalar multiplication or vector addition without additional effort.
Vectors versus tuples
Tuples are a fundamantal part of the language as a fixed-length container that can hold values with different types. Here are some differences between tuples and vectors with some concepts yet to be illustrated.
homogeneous: Vectors hold homogeneous elements of some type,
T; tuples are heterogeneous and can hold values of any type.mathematical: Vectors have scalar multiplication and vector addition defined; tuples do not have mathematical operations defined for them.
iterable: Both vectors and tuples have standard ways to iterate over their components.
indexable: Both vectors and tuples can have their \(i\)th component accessed through indexing.
mutability: Vectors can have the components modified or the length of the underlying object modified. Tuples are immutable. We won’t discuss this here.
storage: Vectors must allocate memory when created, small tuples can be stored on the “stack” and not allocate.
Named tuple
A variant of a tuple is the named tuple where a name can be assigned to each component. For example
nt = (x = 1, y = 2, z = 4)(x = 1, y = 2, z = 4)
The individual components can be accessed by name through “dot” syntax3
nt.y2
5.3.4 Dictionary
A named tuple is an immutable, associative array mapping names (symbols) to values. A dictionary is a general container type for associating a key (of arbitrary type) with a value.
Pair notation in Julia associates a left hand side to a right hand side and is parsed through =>. For example,
pr = 3 => 43 => 4
A dictionary is container to hold pairs:
d = Dict("one" => 1, "two" => 2, "three" => 3)Dict{String, Int64} with 3 entries:
"two" => 2
"one" => 1
"three" => 3
There are other constructors for dictionaries that can prove more convenient.
The basic dictionary is not guaranteed to keep the order of its components, rather it is designed to efficiently lookup a value from a given key. Julia uses square-bracket notation for this lookup.4 For example, the keys of d are strings here we retrieve the value associated to one of them:
d["two"]2
Access will throw a KeyError if the key is not defined.
The collection of keys or the collection of the values can be returned with keys or values:
keys(d)KeySet for a Dict{String, Int64} with 3 entries. Keys:
"two"
"one"
"three"
These are not vectors, however they can be collected into vectors:5
collect(keys(d))3-element Vector{String}:
"two"
"one"
"three"
5.4 Working with containers
Vectors, tuples, and dictionaries are all collections used to group multiple elements into a single unit. Collections in Julia have some commonalities.
First, we define some different collections:
v = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4)
nt = (one=1, two=2, three=3)
d = Dict("one"=>1, "two"=>2)Dict{String, Int64} with 2 entries:
"two" => 2
"one" => 1
5.4.1 Number of elements
The number of elements is returned by length:
length(v), length(t), length(nt), length(d)(5, 4, 3, 2)
A check if there are no elements in the container is done by isempty:
isempty(v), isempty(t), isempty(nt), isempty(d)(false, false, false, false)
5.4.2 Element access
The dictionary and the tuple can have their values accessed by name, as shown. For all but the dictionary, the values have an order (first, second, …).
This order can be reversed, using reverse:
reverse(v), reverse(t), reverse(nt)([5, 4, 3, 2, 1], (4, 3, 2, 1), (three = 3, two = 2, one = 1))
Ordered containers can be accessed by a linear index, starting at 1 for most collections.6
To find the third element, say, we have
v[3], t[3], nt[3](3, 3, 3)
There are also ways to index most collections by specifying more than one element or using a mask of Boolean values to select elements. (A mask is a boolean vector of the same length.)
The collection of indices will be returned as an iterable by keys or eachindex.
Special keywords begin and end can be used to reference the first and last elements of an ordered collection.
v[end], t[end], nt[end](5, 4, 3)
Basic arithmetic can be used with these keywords:7
v[end - 1]4
To access the first and last elements of an ordered collection, there are also first and last methods:
first(v), last(v)(1, 5)
If a container has exactly one element, it can be retrieved generically by only:
only(Dict("a" => 1))"a" => 1
Calling only will error if the container is empty or has more than one element.
5.4.3 Iteration
Each of these collection types can be accessed element by element through iteration. In computer programming a for-loop is the standard way to loop over the values in a collection. We illustrate alternatives.
Destructuring
A common means to name each element of a tuple or vector is to use destructuring. The following sets a to the first value, b to the second, etc.:
a,b,c,d = t(1, 2, 3, 4)
Pairs can be destructured and also first and last are available:
pr = 3 => 4
a, b = pr
a, b, first(pr), last(pr)(3, 4, 3, 4)
Named tuples offer a way to destructure by name:
(; two, three) = nt
three3
This is useful more generally with other data structures.
Named tuples can be constructed directly from variables in a reverse of the above. Notice the leading semicolon:
nt1 = (; two, three)(two = 2, three = 3)
Comprehensions
In mathematics, set notation is often used to describe elements in a set.
For example, the first \(5\) cubed numbers can be described by:
\[ \{x^3: x \text{ in } 1, 2,\dots, 5\} \]
Comprehension notation is similar. The above could be created in Julia with:
xs = [1, 2, 3, 4, 5]
[x^3 for x in xs]5-element Vector{Int64}:
1
8
27
64
125
Comprehensions are one way of iterating over a collection and evaluating an expression on each element.
In the above, the value x takes on each value in xs. The variables may be tuples, as well.
The enumerate method wraps a container (or iterable) and iterates both the index and the value. This is useful, say for polynomials:
x = 3
as = [1, 2, 3] # evaluate a₀⋅x⁰, a₁⋅x¹, a₂⋅x²
[a*x^(i-1) for (i, a) in enumerate(as)]3-element Vector{Int64}:
1
6
27
These values can then be easily summed to evaluate the polynomial:
sum([a*x^(i-1) for (i, a) in enumerate(as)])34
The sum function is a reduction which takes a collection (in this case a comprehension, but more efficiently just the internal generator is needed) and adds the values together. There is a related prod function for finding the product of a collection of numbers.
When iterating over enumerate a tuple is returned at each step. The use of (i, a) to iterate over these tuples destructures the tuple into parts to be used in the expression.
The zip function also is useful to pair off iterators. Redoing the above with powers that start at 0 and using just the generator part of the comprehension we have:
as = [1, 2, 3]
powers = [0, 1, 2]
sum(a*x^i for (i, a) in zip(powers, as))34
Like enumerate, the zip iterator has elements which are tuples. The zip operator is not limited to just two iterables.
The style generally employed herein is to use plural variable names for a collection of values, such as the vector of \(y\) values and singular names when a single value is being referred to, leading to expressions like “x in xs”.
One design choice in Julia is to make numbers iterable. For example
length(3)1
Or even a comprehension:
[x^2 for x in 3]0-dimensional Array{Int64, 0}:
9
(The expression is also an Array but has 0 dimensions, unlike a vector which has 1.)
Broadcasting a function call
If we have a vector, xs, and a function, f, to apply to each value, there is a simple means to achieve this task that is shorter than a for loop or the comprehension [f(x) for x in xs]. Adding a “dot” between the function name and the parenthesis that enclose the arguments, instructs Julia to “broadcast” the function call. The details allow for more much flexibility, but, for this purpose, broadcasting will take each element in xs and apply f to it, returning a vector of the same size as xs. When more than one argument is involved, broadcasting will try to pad out different sized objects to the same shape. Broadcasting can also efficiently fuse combined function calls.
For example, the following will find, using sqrt, the square root of each value in a vector:
xs = [1, 1, 3, 4, 7]
sqrt.(xs)5-element Vector{Float64}:
1.0
1.0
1.7320508075688772
2.0
2.6457513110645907
This call finds the sine of each number in xs:
sin.(xs)5-element Vector{Float64}:
0.8414709848078965
0.8414709848078965
0.1411200080598672
-0.7568024953079282
0.6569865987187891
For each function call, the .( (and not () after the name is the surface syntax for broadcasting.
Here is an example involving the logarithm of a set of numbers. In astronomy, a logarithm with base \(100^{1/5}\) is used for star brightness. We can use broadcasting to find this value for several values at once through:
ys = [1/5000, 1/500, 1/50, 1/5, 5, 50]
base = (100)^(1/5)
log.(base, ys)6-element Vector{Float64}:
-9.247425010840049
-6.747425010840047
-4.247425010840047
-1.747425010840047
1.747425010840047
4.247425010840047
Broadcasting with multiple arguments allows for mixing of vectors and scalar values, as above, making it convenient when parameters are used. In broadcasting, there are times where it is desirable to treat a container as a scalar-like argument, a common idiom is to wrap that container in a 1-element tuple.
Broadcasting infix operators
The ^ operator is an infix operator. Infix operators can be broadcast, as well, by placing the . prior to the operator, as in:
xs .^ 25-element Vector{Int64}:
1
1
9
16
49
Tuples don’t have built-in arithmetical operations like vectors do, but broadcasting can be used to give tuples scalar multiplication and vector addition. First we define two tuples of the same length then use broadcasting to add component-by-component:
a, b = (1,2,3), (1,4,9)
a .+ b(2, 6, 12)
For scalar multiplication, we have:
2 .* a # space needed between "2" and the "."(2, 4, 6)
Broadcasting can be used over various shaped objects. Consider a vector of vector elements:
xs = [1, 2, 3]
vv = [xs, xs.^2, xs.^3]3-element Vector{Vector{Int64}}:
[1, 2, 3]
[1, 4, 9]
[1, 8, 27]
The last element of each element can be retrieved by broadcasting last:
last.(vv)3-element Vector{Int64}:
3
9
27
To get the first, broadcasting first can be done. What about the second? The underlying getindex function can be used. In this example the scalar value 2 is padded out to match the length of vv:
getindex.(vv, 2)3-element Vector{Int64}:
2
4
8
As a final example, the task from statistics of centering and then squaring can be done with broadcasting. We go a bit further, showing how to compute the sample variance of a data set. This has the formula
\[ \frac{1}{n-1}\cdot ((x_1-\bar{x})^2 + \cdots + (x_n - \bar{x})^2). \]
This can be computed, with broadcasting, through:
xs = [1, 1, 2, 3, 5, 8, 13]
n = length(xs)
xbar = sum(xs) / n
ds = xs .- xbar
(1/(n-1)) * sum(ds.^2)19.57142857142857
This shows many of the manipulations that can be made with vectors. We subtracted the scalar mean from the vector of data using broadcasting. Without the ., this subtraction of mixed lengths would error. We then added these values after squaring. Of course this could be done with just one command, like (xs .- xbar).^2. There are more efficient ways of computing this, as there are intermediate arrays created, but this faithfully follows the formula.
Broadcasting is a widely used and powerful surface syntax which we will employ occasionally in the sequel.
Mapping a function over a collection
The map function is very much related to broadcasting, in that it applies a function to each element of an iterable. When more than one iterable is specified, map applies the function to the zipped iterables. Unlike broadcasting, map does not reshape the underlying iterables.
Similarly named functions are found in many different programming languages, as map is one of the foundational higher-order, functional programming operations. (The “dot” broadcast is mostly limited to Julia and mirrors a similar usage of a dot in MATLAB.) For those familiar with other programming languages, using map may seem more natural. Its syntax is map(f, xs). Additional iterables are passed after xs.
For example, this will map sin over each value in xs, computing the same things as sin.(xs):
xs = [0, pi/6, pi/4, pi/3, pi/2]
map(sin, xs)5-element Vector{Float64}:
0.0
0.49999999999999994
0.7071067811865475
0.8660254037844386
1.0
The map function can also be used in combination with reduce, a reduction. Reductions take a container with one or more dimensions and reduces the number of dimensions. An example might be:
sum(map(sin, xs))3.0731321849709863
This has a performance drawback—there are two passes through the container, one to apply sin another to add.
For this task, the sum reduction, as others, allows a function to be specified that is applied to each value in the container while the sum is being computed. This argument comes first. A recommended alternative to the previous would be:
sum(sin, xs)3.0731321849709863
The mapreduce method more generally combines the map and reduce operations in one pass and is called by the above form. The mapreduce method takes a third argument to reduce by in the second position. This is a binary operator. So this combination will map sin over xs and then add the results up sequentially:
mapreduce(sin, +, xs)3.0731321849709863
5.5 Questions
Question
Which command will create the vector \(\vec{v} = \langle 4,~ 3 \rangle\)?
Question
Which command will create the vector with components “4,3,2,1”?
Question
What is the magnitude of the vector \(\vec{v} = \langle 10,~ 15 \rangle\)?
Question
Which of the following is the unit vector in the direction of \(\vec{v} = \langle 3,~ 4 \rangle\)?
Question
What vector is in the same direction as \(\vec{v} = \langle 3,~ 4 \rangle\) but is 10 times as long?
Question
If \(\vec{v} = \langle 3,~ 4 \rangle\) and \(\vec{w} = \langle 1,~ 2 \rangle\) find \(2\vec{v} + 5 \vec{w}\).
Question
Let v be defined by:
v = [1, 1, 2, 3, 5, 8, 13, 21]What is the length of v?
What is the sum of v?
What is the prod of v?
Question
From transum.org.
Figure 5.3 shows \(5\) vectors.
Express vector \(\vec{c}\) in terms of \(\vec{a}\) and \(\vec{b}\):
Express vector \(\vec{d}\) in terms of \(\vec{a}\) and \(\vec{b}\):
Express vector \(\vec{e}\) in terms of \(\vec{a}\) and \(\vec{b}\):
Question
If xs=[1, 2, 3, 4] and f(x) = x^2 which of these will not produce the vector [1, 4, 9, 16]?
Question
Let \(f(x) = \sin(x)\) and \(g(x) = \cos(x)\). In the interval \([0, 2\pi]\) the zeros of \(g(x)\) are given by
zs = [pi/2, 3pi/2]2-element Vector{Float64}:
1.5707963267948966
4.71238898038469
What construct will give the function values of \(f\) at the zeros of \(g\)?
Question
If zs = [1,4,9,16] which of these commands will return [1.0, 2.0, 3.0, 4.0]?
Question
Comprehensions mirror set notation and return a vector (as illustrated). There are some methods for working with collections a sets that may be of interest.
Consider this vector:
ps = [2, 3, 5, 7, 11, 13, 17]What does this expression test?
5 in psNow consider this additional vector
odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]What does this command compute?
intersect(odds, ps)(There are also union and setdiff methods along with intersect.)
The diacritical arrow mark indicates a vector. Alternatively, vector names may be typset in boldface. Both are a means to distinguish from a scalar or number↩︎
A
NTupleis a tuple with a fixed length where each element has the same type.↩︎The dot syntax
nt.aresolves togetproperty(nt, :a),:abeing a symbol.↩︎Square brackets used for access resolve to
getindex, which is defined for many different container types.↩︎The
collectmethod takes an iterator and collects the values into an array, in this example a vector.↩︎Juliais a 1-based language, so most counting starts at1, but this can be modified for a given type by defining afirstindexmethod for the type.↩︎When parsed, these keywords lower to a call of
firstindexorlastindexand the value returned is used in the arithmetic.↩︎