# Points, vectors, and containers


{{< include ../_common_code.qmd >}}

```{julia}
#| echo: false
#| results: "hidden"
using CalculusWithJulia
using Plots
gr() # static images throughout
using Measures
using LaTeXStrings
using LinearAlgebra
nothing
```

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.

## 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.

## 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$^[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].

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.




### 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.

::: {.definition title="The norm of a vector"}
$$
\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.

::: {.definition title="Scalar multiplication"}

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.

:::

::: {.definition title="Vector addition"}

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 @fig-scalar-multiplication-vector-addition.

::: {#fig-scalar-multiplication-vector-addition}

```{julia}
#| echo: false
let
    plt = plot(;
               xaxis=([], false),
               yaxis=([], false),
               framestyle=:origin,
               legend=false)
    P = (0,0)
    v = (1, 2)
    d = norm(v)
    v̂ = v ./ d
    scatter!(plt, [P]; marker=(4,:black))
    plot!(plt, [P, v]; line=(3, :black), arrow=true)
    plot!(plt, [P, (2).*v]; line=(1, :blue), arrow=true)
    plot!(plt, [P, (-1).*v]; line=(1, :red), arrow=true)
    annotate!(plt,
              [(P..., text(L"P", :top)),
               (((1/2).*v)..., text(L"\vec{v}", :top)),
               (((-1/2).*v)..., text(L"-\vec{v}", :top)),
               (((1 + 1/2).* v)..., text(L"2\vec{v}", :top))])

    P = (0,0)
    v = (1, 2)
    w = (2, 1)
    vw = v .+ w
    plt2 = plot(;
                xaxis=([], false),
                yaxis=([], false),
                framestyle=:origin,
                legend=false)
    scatter!(plt2, [P]; marker=(4, :black))
    plot!(plt2, [P, v]; arrow=true, line=(2, :red))
    plot!(plt2, [v, vw]; arrow=true, line=(2, :blue))
    plot!(plt2, [P, vw]; arrow=true, line=(2, :black))
    annotate!(plt2,
              [(P..., text(L"P", :top)),
               (((1/2).*v)..., text(L"\vec{v}", :top)),
               ((v .+ (1/2).*w)..., text(L"\vec{w}", :top)),
               ((1/2) .* vw..., text(L"\vec{v} + \vec{w}", :top, :left))
               ])

    plot(plt, plt2)
end
```


The left figure shows vector $\vec{v}$, $-\vec{v}$, and the vector $2\vec{v}$ all anchored at $P$. The vector $-\vec{v}$ has the same magnitude but opposite direction as $\vec{v}$; the vector $2\vec{v}$ has the same direction but double the magnitude as $\vec{v}$. The right figure visualizes $\vec{v} + \vec{w}$ by drawing $\vec{w}$ anchored at the top of $\vec{v}$ and viewing the new vector from $P$ to the tip of $\vec{w}$.
:::

### 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](http://tinyurl.com/8ylk29t) 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.


::: {#fig-projectile-motion  layout-ncol=1}
```{julia}
#| hold: true
#| echo: false

gr()
px = 0.26mm
x0 = [0, 64]
v0 = [20, 0]
g  = [0, -32]

unit(v::Vector) = v / norm(v)
x_ticks = collect(0:10:80)
y_ticks = collect(0:10:80)


function make_plot(t)

    xn = (t) -> x0 + v0*t + 1/2*g*t^2
    vn = (t) -> v0 + g*t
    an = (t) -> g


    t = 1/10 + t*2/10

    ts = range(0, stop=t, length=100)
    xys = map(xn, ts)

    xs, ys = [p[1] for p in xys], [p[2] for p in xys]


    plt = plot(;legend=false, size=fig_size, xlims=(0,45), ylims=(0,75))
    plot!(plt, xs, ys; line=(1, :black))

    ts = range(t, 2, length=100)
    xys = map(xn, ts)
    xs, ys = [p[1] for p in xys], [p[2] for p in xys]
    plot!(plt, xs, ys; line=(:dot, 1, :gray))

    plot!(plt, zero, extrema(xs)...)
    #arrow!(xn(t), 10*unit(xn(t)), color="black")
    scatter!([Tuple(xn(t))]; marker=(5, :black))
    arrow!(0*xn(t), xn(t); color="black")
    arrow!(xn(t), 10*unit(vn(t)), color="red")
    arrow!(xn(t), 10*unit(an(t)), color="green")

    plt


end

imgfile = tempname() * ".gif"

n = 8
anim = @animate for i=1:1/2:n
    make_plot(i)
end

gif(anim, imgfile, fps = 2)

plotly()
ImageFile(imgfile)
```

Position, velocity, and acceleration vectors (scaled) for projectile
motion. Vectors are drawn with tail on the projectile. The position
vector (black) points from the origin to the projectile, the velocity
vector (red) is in the direction of the trajectory, and the
acceleration vector (green) is a constant pointing downward.
:::

For the motion in @fig-projectile-motion, 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.

@fig-projectile-motion 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.


### 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}}
$$


## Containers

`Julia` has multiple data structures available. In this discussion we focus on a few foundational containers used to hold different collections.

### 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:

```{julia}
v = [1, 2, 3]             # 𝐯 = ⟨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:

```{julia}
w = [3, 2, 1]
2*v, v + w
```

The dot product and the norm functionality are found in the standard library `LinearAlgebra`. This must be loaded in order to be used:

```{julia}
using LinearAlgebra
```

Once loaded, we can access these features as follows:

```{julia}
dot(v, w), norm(v), sqrt(dot(v,v))
```

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.jl` package takes text and produces tokens from the words.

* a vector of Boolean values can naturally arise and is widely used within Julia's `DataFrames.jl` package.

* 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.


```{julia}
["one", "two", "three"] # T is String
```

```{julia}
[true, false, true]		# T is Bool for Boolean values
```



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`:


```{julia}
[1, 2.0, 3//1]
```

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.


```{julia}
["one", 2, 3.0, 4//1]
```



### 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.


### 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

```{julia}
P = (1, 2, 3)
```

Tuples can hold values of different types^[A `NTuple` is a tuple with a fixed length where each element has the same type.]:

```{julia}
Q = (true, 1, pi)
```

A $1$ element tuple is constructed with a comma as follows:

```{julia}
R = (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

```{julia}
nt = (x = 1, y = 2, z = 4)
```

The individual components can be accessed by name through "dot" syntax^[The dot syntax `nt.a` resolves to `getproperty(nt, :a)`, `:a` being a symbol.]

```{julia}
nt.y
```

### 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,

```{julia}
pr = 3 => 4
```

A dictionary is container to hold pairs:


```{julia}
d = Dict("one" => 1, "two" => 2, "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.^[Square brackets used for access resolve to `getindex`, which is defined for many different container types.]  For example, the keys of `d` are strings here we retrieve the value associated to one of them:

```{julia}
d["two"]
```

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`:

```{julia}
keys(d)
```

These are *not* vectors, however they can be collected into vectors:^[The `collect` method takes an iterator and collects the values into an array, in this example a vector.]

```{julia}
collect(keys(d))
```


## 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:

```{julia}
v = [1, 2, 3, 4, 5]
t = (1, 2, 3, 4)
nt = (one=1, two=2, three=3)
d = Dict("one"=>1, "two"=>2)
```

### Number of elements

The number of elements is returned by `length`:

```{julia}
length(v), length(t), length(nt), length(d)
```

A check if there are no elements in the container is done by `isempty`:

```{julia}
isempty(v), isempty(t), isempty(nt), isempty(d)
```

### 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`:

```{julia}
reverse(v), reverse(t), reverse(nt)
```


Ordered containers can be accessed by a linear index, starting at `1` for most collections.^[`Julia` is a 1-based language, so most counting starts at `1`, but this can be modified for a given type by defining a `firstindex` method for the type.]

To find the third element, say, we have

```{julia}
v[3], t[3], nt[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.

```{julia}
v[end], t[end], nt[end]
```

Basic arithmetic can be used with these keywords:^[When parsed, these keywords lower to a call of `firstindex` or `lastindex` and the value returned is used in the arithmetic.]

```{julia}
v[end - 1]
```

To access the first and last elements of an ordered collection, there are also `first` and `last` methods:

```{julia}
first(v), last(v)
```

If a container has exactly one element, it can be retrieved generically by `only`:

```{julia}
only(Dict("a" => 1))
```

Calling `only` will error if the container is empty or has more than one element.

### 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.:

```{julia}
a,b,c,d = t
```

Pairs can be destructured and also `first` and `last` are available:


```{julia}
pr = 3 => 4
a, b = pr
a, b, first(pr), last(pr)
```


Named tuples offer a way to destructure by name:

```{julia}
(; two, three) = nt
three
```

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:

```{julia}
nt1 = (; two, three)
```

#### 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:


```{julia}
xs = [1, 2, 3, 4, 5]
[x^3 for x in xs]
```

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:

```{julia}
x = 3
as = [1, 2, 3] # evaluate a₀⋅x⁰, a₁⋅x¹, a₂⋅x²
[a*x^(i-1) for (i, a) in enumerate(as)]
```

These values can then be easily summed to evaluate the polynomial:

```{julia}
sum([a*x^(i-1) for (i, a) in enumerate(as)])
```

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:

```{julia}
as = [1, 2, 3]
powers = [0, 1, 2]
sum(a*x^i for (i, a) in zip(powers, as))
```

Like `enumerate`, the `zip` iterator has elements which are tuples. The `zip` operator is not limited to just two iterables.

:::{.callout-note}
## Note
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`".

:::

:::{.callout-note}
## Numbers are iterable

One design choice in `Julia` is to make numbers iterable. For example

```{julia}
length(3)
```

Or even a comprehension:

```{julia}
[x^2 for x in 3]
```

(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:


```{julia}
xs = [1, 1, 3, 4, 7]
sqrt.(xs)
```

This call finds the sine of each number in `xs`:


```{julia}
sin.(xs)
```

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](http://tinyurl.com/ycp7k8ay). We can use broadcasting to find this value for several values at once through:


```{julia}
ys = [1/5000, 1/500, 1/50, 1/5, 5, 50]
base = (100)^(1/5)
log.(base, ys)
```

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:


```{julia}
xs .^ 2
```


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:

```{julia}
a, b = (1,2,3), (1,4,9)
a .+ b
```

For scalar multiplication, we have:

```{julia}
2 .* a       # space needed between "2" and the  "."
```


Broadcasting can be used over various shaped objects. Consider a vector of vector elements:

```{julia}
xs = [1, 2, 3]
vv = [xs, xs.^2, xs.^3]
```

The last element of each element can be retrieved by broadcasting `last`:

```{julia}
last.(vv)
```

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`:

```{julia}
getindex.(vv, 2)
```


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](http://tinyurl.com/p6wa4r8) 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:


```{julia}
#| hold: true
xs = [1, 1, 2, 3, 5, 8, 13]
n = length(xs)
xbar = sum(xs) / n
ds = xs .- xbar
(1/(n-1)) * sum(ds.^2)
```

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 `zip`ped 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)`:

```{julia}
xs = [0, pi/6, pi/4, pi/3, pi/2]
map(sin, xs)
```

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:

```{julia}
sum(map(sin, xs))
```

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:

```{julia}
sum(sin, xs)
```

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:

```{julia}
mapreduce(sin, +, xs)
```


## Questions


###### Question


Which command will create the vector $\vec{v} = \langle 4,~ 3 \rangle$?


```{julia}
#| hold: true
#| echo: false
choices = [
q"v = [4,3]",
q"v = {4, 3}",
q"v = '4, 3'",
q"v = (4,3)",
q"v = <4,3>"]
answ = 1
radioq(choices, answ)
```

###### Question


Which command will create the vector with components "4,3,2,1"?


```{julia}
#| hold: true
#| echo: false
choices = [q"v = [4,3,2,1]", q"v = (4,3,2,1)", q"v = {4,3,2,1}", q"v = '4, 3, 2, 1'", q"v = <4,3,2,1>"]
answ = 1
radioq(choices, answ)
```

###### Question


What is the magnitude of the vector $\vec{v} = \langle 10,~ 15 \rangle$?


```{julia}
#| hold: true
#| echo: false
v = [10, 15]
val = norm(v)
numericq(val)
```

###### Question


Which of the following is the unit vector in the direction of $\vec{v} = \langle 3,~ 4 \rangle$?


```{julia}
#| hold: true
#| echo: false
choices = [q"[3, 4]", q"[0.6, 0.8]", q"[1.0, 1.33333]", q"[1, 1]"]
answ = 2
radioq(choices, answ)
```

###### Question


What vector is in the same direction as $\vec{v} = \langle 3,~ 4 \rangle$ but is 10 times as long?


```{julia}
#| hold: true
#| echo: false
choices = [q"[3, 4]", q"[30, 40]", q"[9.48683, 12.6491]", q"[10, 10]"]
answ = 2
radioq(choices, answ)
```

###### Question


If $\vec{v} = \langle 3,~ 4 \rangle$ and $\vec{w} = \langle 1,~ 2 \rangle$  find $2\vec{v} + 5 \vec{w}$.


```{julia}
#| hold: true
#| echo: false
choices = [q"[4, 6]", q"[6, 8]", q"[11, 18]", q"[5, 10]"]
answ = 3
radioq(choices, answ)
```

###### Question


Let `v` be defined by:


```{julia}
#| hold: true
#| eval: false
v = [1, 1, 2, 3, 5, 8, 13, 21]
```

What is the length of `v`?


```{julia}
#| hold: true
#| echo: false
v = [1, 1, 2, 3, 5, 8, 13, 21]
val = length(v)
numericq(val)
```

What is the `sum` of `v`?


```{julia}
#| hold: true
#| echo: false
v = [1, 1, 2, 3, 5, 8, 13, 21]
val = sum(v)
numericq(val)
```

What is the `prod` of `v`?


```{julia}
#| hold: true
#| echo: false
v = [1,1,2,3,5,8,13,21]
val = prod(v)
numericq(val)
```

###### Question


From [transum.org](http://www.transum.org/Maths/Exam/Online_Exercise.asp?Topic=Vectors).

::: {#fig-identify-superpositions-of-vectors-transum}
```{julia}
#| hold: true
#| echo: false
let
    gr()
p = plot(xlim=(0,10), ylim=(0,5), legend=false, framestyle=:none)
for j in (-3):10
    plot!(p, [j, j + 5], [0, 5*sqrt(3)], color=:blue, alpha=0.5)
    plot!(p, [j - 5, j], [5*sqrt(3), 0], color=:blue, alpha=0.5)
end
for i in 1/2:1/2:3
    plot!(p, [0,10],sqrt(3)*[i,i], color=:blue, alpha=0.5)
end

quiver!(p, [(3/2, 3/2*sqrt(3))], quiver=[(1,0)], color=:black,  linewidth=5)        # a
quiver!(p, [(2, sqrt(3))], quiver=[(1/2,-sqrt(3)/2)], color=:black,  linewidth=5)   # b

quiver!(p, [(3 + 3/2, 3/2*sqrt(3))], quiver=[(3,0)], color=:black,  linewidth=5)        # c
quiver!(p, [(4 , sqrt(3))], quiver=[(3/2,-sqrt(3)/2)], color=:black,  linewidth=5)        # d
quiver!(p, [(6+1/2 , sqrt(3)/2)], quiver=[(1/2, sqrt(3)/2)], color=:black,  linewidth=5)        # e

delta = 1/4
annotate!(p, [(2, 3/2*sqrt(3) -delta, L"\vec{a}"),
              (2+1/4, sqrt(3), L"\vec{b}"),
              (3+3/2+3/2, 3/2*sqrt(3)-delta, L"\vec{c}"),
              (4+3/4, sqrt(3) - sqrt(3)/4-delta, L"\vec{d}"),
              (6+3/4+delta, sqrt(3)/2 + sqrt(3)/4-delta, L"\vec{e}")
              ])


    p
end
```

Vectors on a non-Cartesian grid
:::

@fig-identify-superpositions-of-vectors-transum shows $5$ vectors.


Express vector $\vec{c}$ in terms of $\vec{a}$ and $\vec{b}$:


```{julia}
#| hold: true
#| echo: false
choices = [L"3\vec{a}", L"3\vec{b}", L"\vec{a} + \vec{b}", L"\vec{a} - \vec{b}", L"\vec{b}-\vec{a}"]
answ = 1
radioq(choices, answ)
```

Express vector $\vec{d}$ in terms of $\vec{a}$ and $\vec{b}$:


```{julia}
#| hold: true
#| echo: false
choices = [L"3\vec{a}", L"3\vec{b}", L"\vec{a} + \vec{b}", L"\vec{a} - \vec{b}", L"\vec{b}-\vec{a}"]
answ = 3
radioq(choices, answ)
```

Express vector $\vec{e}$ in terms of $\vec{a}$ and $\vec{b}$:


```{julia}
#| hold: true
#| echo: false
choices = [L"3\vec{a}", L"3\vec{b}", L"\vec{a} + \vec{b}", L"\vec{a} - \vec{b}", L"\vec{b}-\vec{a}"]
answ = 4
radioq(choices, answ)
```

```{julia}
#| echo: false
plotly()
nothing
```

###### Question


If `xs=[1, 2, 3, 4]` and `f(x) = x^2` which of these will not produce the vector `[1, 4, 9, 16]`?


```{julia}
#| hold: true
#| echo: false
choices = [q"f.(xs)", q"map(f, xs)", q"[f(x) for x in xs]", "All three of them work"]
answ = 4
radioq(choices, answ, keep_order=true)
```

###### 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


```{julia}
zs = [pi/2, 3pi/2]
```

What construct will give the function values of $f$ at the zeros of $g$?


```{julia}
#| hold: true
#| echo: false
choices = [q"sin(zs)", q"sin.(zs)", q"sin(.zs)", q".sin(zs)"]
answ = 2
radioq(choices, answ, keep_order=true)
```

###### Question


If `zs = [1,4,9,16]` which of these commands will return `[1.0, 2.0, 3.0, 4.0]`?


```{julia}
#| hold: true
#| echo: false
choices = [
q"sqrt(zs)",
q"sqrt.(zs)",
q"zs^(1/2)",
q"zs^(1./2)"
]
answ = 2
radioq(choices, answ, keep_order=true)
```


###### 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:

```{julia}
#| eval: false
ps = [2, 3, 5, 7, 11, 13, 17]
```

What does this expression test?

```{julia}
#| eval: false
5 in ps
```

```{julia}
#| echo: false
choices = ["It tests inclusion---is `5` in the  collection",
           "It errors"]
answer = 1
buttonq(choices, answer)
```

Now consider this additional vector

```{julia}
#| eval: false
odds = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
```

What does this command compute?

```{julia}
#| eval: false
intersect(odds, ps)
```

```{julia}
#| echo: false
choices = ["It finds the *intersection* of the two vectors as sets",
           "It finds the *union* of the the two vectors as sets",
           "It finds the *set difference* of the the two vectors as sets"]
answer = 1
buttonq(choices, answer)
```

(There are also `union` and `setdiff` methods along with `intersect`.)
