# Graph Theory

## Hamilton Paths

### Learning Objectives

After completing this section, you should be able to:
1. Describe and identify Hamilton paths.
2. Evaluate Hamilton paths in real-world applications.
3. Distinguish between Hamilton paths and Euler trails.
In the United States, school buses carry 25 million children between school and home every day. The total distance they travel is around 6 billion kilometers per year. In the city of Boston, Massachusetts, the 2016 budget for running those buses was $120 million dollars. In 2017, the city held a competition to find ways to cut costs and the Quantum Team from the MIT Operations Research Center came to the rescue, using a computer algorithm to identify the most efficient and least costly routes, which saved the city of Boston $5 million each year and even reduced daily CO2 emissions by 9,000 kilograms! (This U.S. city put an algorithm in charge of its school bus routes and saved $5 million, Sean Fleming, World Economic Forum)
The problem the Quantum Team tackled involves graph theory. Imagine a graph in which vertices are the bus depot, the school, and the bus stops along a particular route. The bus must start at the depot, visit every stop exactly once, and end at the school. The route is a special kind of path that visits every vertex exactly once. Can you guess what those paths are called?

### Hamilton Paths

Just as circuits that visit each vertex in a graph exactly once are called Hamilton cycles (or Hamilton circuits), paths that visit each vertex on a graph exactly once are called Hamilton paths. As we explore Hamilton paths, you might find it helpful to refresh your memory about the relationships between walks, trails, and paths by looking at . We know that paths are walks that don’t repeat any vertices or edges. So, a Hamilton path visits every vertex without repeating any vertices or edges.  shows a path from vertex A to vertex E and a Hamilton path from vertex A to vertex E.

### Finding Hamilton Paths

Suppose you were visiting an aquarium with some friends. The map of the aquarium is given in . The letters represent the exhibits.
 shows a graph of the aquarium in which each vertex represents an exhibit and each edge is a route between the pair of exhibits that doesn’t bypass another exhibit.
Let’s see if we can plan a tour of the exhibits that visits each exhibit exactly once, beginning at exhibit O and ending at exhibit C. Suppose that, after exhibit O, we plan to visit exhibit Q and then exhibit M. After M, should we plan to visit N, L, or R? Take a look at . If R is not chosen next, that will cause a problem later on. Do you see what it is?
If L or N is chosen next, the only way to get to R later will be to go from S to R, and then we will not be able to continue without repeating a vertex. So, we will pick R next, and then the only option is S. After S we have another choice to make. As shown in , the next choice is between B and E. Keeping in mind that the goal is to end at C, which would be the better choice?
If you said vertex B, you are right! Otherwise, we will not be able to visit B later. After B, the only option is E. Then we can choose either D or G. Either will work fine. Let’s choose G as shown in . After G, you must visit H, but should you visit K or L after that?
If you said to go to vertex L next, you are right! Otherwise, it will be impossible to visit N without repeating a vertex. So, next is L, then N, then K, and then at J you have another decision to make we can see in . Should you choose F, I, or P next?
If you said P, you are right! If you choose either of the other two vertices, you will not be able to visit P later without passing through another vertex twice. Once P is chosen, vertex I must be next followed by F. Then you have to choose between A and D as shown in .
In this case, we must go to D then to A so that we can visit C without backtracking. The complete Hamilton path is shown in .
So, one Hamilton path that begins at O and ends at C is O → Q → M → R → S → B → E → G → H → L → N → K → J → P → I → F → D → A → C.
There is no set sequence of steps that can be used to find a Hamilton path if it exists, but it does help to keep in mind where we are headed and avoid choices that will make returning to a particular vertex impossible without repeating vertices. Let’s practice finding Hamilton paths.

### Existence of a Hamilton Path

It turns out that there is no Hamilton path between vertices A and E in Graph G in . To understand why, let’s imagine there is a red apple tree on one side of a bridge and a green apple tree on the other side of the bridge. Now suppose someone asked you to pick up all the fallen apples under each tree without crossing the bridge more than once, and making sure that the first apple you pick up and the last apple you pick up are both red. You would say, that is impossible! To have the first and last apple be red would either require leaving the green apples on the ground or crossing the bridge twice.
Let’s see how this relates to finding a Hamilton path between A and E in Graph G. The edge AC is a bridge because, if it were removed, the graph would become disconnected with two components, the component {C} and the component {A, B, D, E, F}. So, we can think of the vertices A, B, D, E, and F as the red apples, vertex C as the green apple, and the edge AC is the bridge between them as in .
The creation of a Hamilton path requires a visit to each vertex, just as picking up all the apples requires a visit to each apple. A and E are both red apples; so, a path from A to E would both start and end at a red apple, just as you were asked to do. And you wouldn’t be able to cross the bridge twice because that would mean visiting A twice, which is not allowed in a Hamilton path. So, it is impossible to find a Hamilton path from A to E just as it was impossible to pick up all the apples without crossing the bridge more than once. By the same reasoning, if a graph has a bridge, there will never be a Hamilton path that begins and ends on the same side of that bridge, meaning beginning and ending at vertices that would be in the same component if the bridge were removed from the graph.
There is not a short way to determine if there is a Hamilton path between two vertices on a graph that works in every situation. However, there are a few common situations that can help us to quickly determine that there is no Hamilton path. Some of these are listed in .

### Hamilton Path or Euler Trail?

We learned in Euler Trails that an Euler trail visits each edge exactly once, whereas a Hamilton path visits each vertex exactly once. Let’s practice distinguishing between the two.

### Check Your Understanding

### Key Terms

1. Hamilton path

### Key Concepts

1. A Hamilton path visits every vertex exactly once.
2. Some Hamilton paths are also Euler trails, but some are not.


# Graph Theory

## Traveling Salesperson Problem

### Learning Objectives

After completing this section, you should be able to:
1. Distinguish between brute force algorithms and greedy algorithms.
2. List all distinct Hamilton cycles of a complete graph.
3. Apply brute force method to solve traveling salesperson applications.
4. Apply nearest neighbor method to solve traveling salesperson applications.
We looked at Hamilton cycles and paths in the previous sections Hamilton Cycles and Hamilton Paths. In this section, we will analyze Hamilton cycles in complete weighted graphs to find the shortest route to visit a number of locations and return to the starting point. Besides the many routing applications in which we need the shortest distance, there are also applications in which we search for the route that is least expensive or takes the least time. Here are a few less common applications that you can read about on a website set up by the mathematics department at the University of Waterloo in Ontario, Canada:
1. Design of fiber optic networks
2. Minimizing fuel expenses for repositioning satellites
3. Development of semi-conductors for microchips
4. A technique for mapping mammalian chromosomes in genome sequencing
Before we look at approaches to solving applications like these, let's discuss the two types of algorithms we will use.

### Brute Force and Greedy Algorithms

An algorithm is a sequence of steps that can be used to solve a particular problem. We have solved many problems in this chapter, and the procedures that we used were different types of algorithms. In this section, we will use two common types of algorithms, a brute force algorithm and a greedy algorithm. A brute force algorithm begins by listing every possible solution and applying each one until the best solution is found. A greedy algorithm approaches a problem in stages, making the apparent best choice at each stage, then linking the choices together into an overall solution which may or may not be the best solution.
To understand the difference between these two algorithms, consider the tree diagram in . Suppose we want to find the path from left to right with the largest total sum. For example, branch A in the tree diagram has a sum of .
To be certain that you pick the branch with greatest sum, you could list each sum from each of the different branches:
A:
B:
C:
D:
E:
F:
G:
H:
Then we know with certainty that branch E has the greatest sum.
Now suppose that you wanted to find the branch with the highest value, but you only were shown the tree diagram in phases, one step at a time.
After phase 1, you would have chosen the branch with 10 and 7. So far, you are following the same branch. Let’s look at the next phase.
After phase 2, based on the information you have, you will choose the branch with 10, 7 and 4. Now, you are following a different branch than before, but it is the best choice based on the information you have. Let’s look at the last phase.
After phase 3, you will choose branch G which has a sum of 32.
The process of adding the values on each branch and selecting the highest sum is an example of a brute force algorithm because all options were explored in detail. The process of choosing the branch in phases, based on the best choice at each phase is a greedy algorithm. Although a brute force algorithm gives us the ideal solution, it can take a very long time to implement. Imagine a tree diagram with thousands or even millions of branches. It might not be possible to check all the sums. A greedy algorithm, on the other hand, can be completed in a relatively short time, and generally leads to good solutions, but not necessarily the ideal solution.

### The Traveling Salesperson Problem

Now let’s focus our attention on the graph theory application known as the traveling salesperson problem (TSP) in which we must find the shortest route to visit a number of locations and return to the starting point.
Recall from Hamilton Cycles, the officer in the U.S. Air Force who is stationed at Vandenberg Air Force base and must drive to visit three other California Air Force bases before returning to Vandenberg. The officer needed to visit each base once. We looked at the weighted graph in  representing the four U.S. Air Force bases: Vandenberg, Edwards, Los Angeles, and Beal and the distances between them.
Any route that visits each base and returns to the start would be a Hamilton cycle on the graph. If the officer wants to travel the shortest distance, this will correspond to a Hamilton cycle of lowest weight. We saw in  that there are six distinct Hamilton cycles (directed cycles) in a complete graph with four vertices, but some lie on the same cycle (undirected cycle) in the graph.
Since the distance between bases is the same in either direction, it does not matter if the officer travels clockwise or counterclockwise. So, there are really only three possible distances as shown in .
The possible distances are:
So, a Hamilton cycle of least weight is V → B → E → L → V (or the reverse direction). The officer should travel from Vandenberg to Beal to Edwards, to Los Angeles, and back to Vandenberg.

### Finding Weights of All Hamilton Cycles in Complete Graphs

Notice that we listed all of the Hamilton cycles and found their weights when we solved the TSP about the officer from Vandenberg. This is a skill you will need to practice. To make sure you don't miss any, you can calculate the number of possible Hamilton cycles in a complete graph. It is also helpful to know that half of the directed cycles in a complete graph are the same cycle in reverse direction, so, you only have to calculate half the number of possible weights, and the rest are duplicates.

### The Brute Force Method

The method we have been using to find a Hamilton cycle of least weight in a complete graph is a brute force algorithm, so it is called the brute force method. The steps in the brute force method are:
Step 1: Calculate the number of distinct Hamilton cycles and the number of possible weights.
Step 2: List all possible Hamilton cycles.
Step 3: Find the weight of each cycle.
Step 4: Identify the Hamilton cycle of lowest weight.
Now suppose that the officer needed a cycle that visited all 5 of the Air Force bases in . There would be  different arrangements of vertices and  distances to compare using the brute force method. If you consider 10 Air Force bases, there would be  different arrangements and  distances to consider. There must be another way!

### The Nearest Neighbor Method

When the brute force method is impractical for solving a traveling salesperson problem, an alternative is a greedy algorithm known as the nearest neighbor method, which always visit the closest or least costly place first. This method finds a Hamilton cycle of relatively low weight in a complete graph in which, at each phase, the next vertex is chosen by comparing the edges between the current vertex and the remaining vertices to find the lowest weight. Since the nearest neighbor method is a greedy algorithm, it usually doesn’t give the best solution, but it usually gives a solution that is "good enough." Most importantly, the number of steps will be the number of vertices. That’s right! A problem with 10 vertices requires 10 steps, not 362,880. Let’s look at an example to see how it works.
Suppose that a candidate for governor wants to hold rallies around the state. They plan to leave their home in city A, visit cities B, C, D, E, and F each once, and return home. The airfare between cities is indicated in the graph in .
Let’s help the candidate keep costs of travel down by applying the nearest neighbor method to find a Hamilton cycle that has a reasonably low weight. Begin by marking starting vertex as  for "visited 1st." Then to compare the weights of the edges between A and vertices adjacent to A: $250, $210, $300, $200, and $100 as shown in . The lowest of these is $100, which is the edge between A and F.
Mark F as  for "visited 2nd" then compare the weights of the edges between F and the remaining vertices adjacent to F: $170, $330, $150 and $350 as shown in . The lowest of these is $150, which is the edge between F and D.
Mark D as  for "visited 3rd." Next, compare the weights of the edges between D and the remaining vertices adjacent to D: $120, $310, and $270 as shown in . The lowest of these is $120, which is the edge between D and B.
So, mark B as  for "visited 4th." Finally, compare the weights of the edges between B and the remaining vertices adjacent to B: $160 and $220 as shown in . The lower amount is $160, which is the edge between B and E.
Now you can mark E as  and mark the only remaining vertex, which is C, as . This is shown in . Make a note of the weight of the edge from E to C, which is $180, and from C back to A, which is $210.
The Hamilton cycle we found is A → F → D → B → E → C → A. The weight of the circuit is . This may or may not be the route with the lowest cost, but there is a good chance it is very close since the weights are most of the lowest weights on the graph and we found it in six steps instead of finding 120 different Hamilton cycles and calculating 60 weights. Let’s summarize the procedure that we used.
Step 1: Select the starting vertex and label  for "visited 1st." Identify the edge of lowest weight between  and the remaining vertices.
Step 2: Label the vertex at the end of the edge of lowest weight that you found in previous step as  where the subscript n indicates the order the vertex is visited. Identify the edge of lowest weight between  and the vertices that remain to be visited.
Step 3: If vertices remain that have not been visited, repeat Step 2. Otherwise, a Hamilton cycle of low weight is .

### Check Your Understanding

### Key Terms

1. brute force algorithm
2. greedy algorithm
3. traveling salesperson problem (TSP)
4. brute force method
5. nearest neighbor method

### Key Concepts

1. A brute force algorithm always finds the ideal solution but can be impractical whereas a greedy algorithm is efficient but usually does not lead to the ideal solution.
2. A Hamilton cycle of lowest weight is a solution to the traveling salesperson problem.
3. The brute force method finds a Hamilton cycle of lowest weight in a complete graph.
4. The nearest neighbor method is a greedy algorithm that finds a Hamilton cycle of relatively low weight in a complete graph.

### Formulas

1. In a complete graph with  vertices, the number of distinct Hamilton cycles is .
2. In a complete graph with  vertices, there are at most  different weights of Hamilton cycles.


# Graph Theory

## Trees

### Learning Objectives

After completing this section, you should be able to:
1. Describe and identify trees.
2. Determine a spanning tree for a connected graph.
3. Find the minimum spanning tree for a weighted graph.
4. Solve application problems involving trees.
We saved the best for last! In this last section, we will discuss arguably the most fun kinds of graphs, trees. Have you every researched your family tree? Family trees are a perfect example of the kind of trees we study in graph theory. One of the characteristics of a family tree graph is that it never loops back around, because no one is their own grandparent!

### What Is A Tree?

Whether we are talking about a family tree or a tree in a forest, none of the branches ever loops back around and rejoins the trunk. This means that a tree has no cyclic subgraphs, or is acyclic. A tree also has only one component. So, a tree is a connected acyclic graph. Here are some graphs that have the same characteristic. Each of the graphs in  is a tree.
Let’s practice determining whether a graph is a tree. To do this, check if a graph is connected and has no cycles.

### Types of Trees

Mathematicians have had a lot of fun naming graphs that are trees or that contain trees. For example, the graph in  is not a tree, but it contains two components, one containing vertices a through d, and the other containing vertices e through g, each of which would be a tree on its own. This type of structure is called a forest. There are also interesting names for trees with certain characteristics.
1. A path graph or linear graph  is a tree graph that has exactly two vertices of degree 1 such that the only other vertices form a single path between them, which means that it can be drawn as a straight line.
2. A star tree is a tree that has exactly one vertex of degree greater than 1 called a root, and all other vertices are adjacent to it.
3. A starlike tree is a tree that has a single root  and several paths attached to it.
4. A caterpillar tree is a tree that has a central path that can have vertices of any degree, with each vertex not on the central path being adjacent to a vertex on the central path and having a degree of one.
5. A lobster tree is a tree that has a central path that can have vertices of any degree, with paths consisting of either one or two edges attached to the central path.
Examples of each of these types of structures are given in .

### Characteristics of Trees

As we study trees, it is helpful to be familiar with some of their characteristics. For example, if you add an edge to a tree graph between any two existing vertices, you will create a cycle, and the resulting graph is no longer a tree. Some examples are shown in . Adding edge bj to Graph T creates cycle (b, c, i, j). Adding edge rt to Graph P creates cycle (r, s, t). Adding edge tv to Graph S creates cycle (t, u, v).
It is also true that removing an edge from a tree graph will increase the number of components and the graph will no longer be connected. In fact, you can see in  that removing one or more edges can create a forest. Removing edge qr from Graph P creates a graph with two components, one with vertices o, p and q, and the other with vertices r, s, and t. Removing edge uw from Graph S creates two components, one with just vertex w and the other with the rest of the vertices. When two edges were removed from Graph T, edge bf and edge cd, creates a graph with three components as shown in .
A very useful characteristic of tree graphs is that the number of edges is always one less than the number of vertices. In fact, any connected graph in which the number of edges is one less than the number of vertices is guaranteed to be a tree. Some examples are given in .

### Spanning Trees

Suppose that you planned to set up your own computer network with four devices. One option is to use a “mesh topology” like the one in , in which each device is connected directly to every other device in the network.
The mesh topology for four devices could be represented by the complete Graph A1 in  where the vertices represent the devices, and the edges represent network connections. However, the devices could be networked using fewer connections. Graphs A2, A3, and A4 of  show configurations in which three of the six edges have been removed. Each of the Graphs A2, A3 and A4 in  is a tree because it is connected and contains no cycles. Since Graphs A2, A3 and A4 are also subgraphs of Graph A1 that include every vertex of the original graph, they are also known as spanning trees.
By definition, spanning trees must span the whole graph by visiting all the vertices. Since spanning trees are subgraphs, they may only have edges between vertices that were adjacent in the original graph. Since spanning trees are trees, they are connected and they are acyclic. So, when deciding whether a graph is a spanning tree, check the following characteristics:
1. All vertices are included.
2. No vertices are adjacent that were not adjacent in the original graph.
3. The graph is connected.
4. There are no cycles.

### Constructing a Spanning Tree Using Paths

Suppose that you wanted to find a spanning tree within a graph. One approach is to find paths within the graph. You can start at any vertex, go any direction, and create a path through the graph stopping only when you can’t continue without backtracking as shown in .
Once you have stopped, pick a vertex along the path you drew as a starting point for another path. Make sure to visit only vertices you have not visited before as shown in .
Repeat this process until all vertices have been visited as shown in .
The end result is a tree that spans the entire graph as shown in .
Notice that this subgraph is a tree because it is connected and acyclic. It also visits every vertex of the original graph, so it is a spanning tree. However, it is not the only spanning tree for this graph. By making different turns, we could create any number of distinct spanning trees.

### Revealing Spanning Trees

Another approach to finding a spanning tree in a connected graph involves removing unwanted edges to reveal a spanning tree. Consider Graph D in .
Graph D has 10 vertices. A spanning tree of Graph D must have 9 edges, because the number of edges is one less than the number of vertices in any tree. Graph D has 13 edges so 4 need to be removed. To determine which 4 edges to remove, remember that trees do not have cycles. There are four triangles in Graph D that we need to break up. We can accomplish this by removing 1 edge from each of the triangles. There are many ways this can be done. Two of these ways are shown in .

### Kruskal’s Algorithm

In many applications of spanning trees, the graphs are weighted and we want to find the spanning tree of least possible weight. For example, the graph might represent a computer network, and the weights might represent the cost involved in connecting two devices. So, finding a spanning tree with the lowest possible total weight, or minimum spanning tree, means saving money! The method that we will use to find a minimum spanning tree of a weighted graph is called Kruskal’s algorithm. The steps for Kruskal’s algorithm are:
Step 1: Choose any edge with the minimum weight of all edges.
Step 2: Choose another edge of minimum weight from the remaining edges. The second edge does not have to be connected to the first edge.
Step 3: Choose another edge of minimum weight from the remaining edges, but do not select any edge that creates a cycle in the subgraph you are creating.
Step 4: Repeat step 3 until all the vertices of the original graph are included and you have a spanning tree.

### Check Your Understanding

### Key Terms

1. acyclic
2. tree
3. forest
4. path graph or linear graph
5. star tree
6. root
7. starlike tree
8. caterpillar tree
9. lobster tree
10. spanning tree
11. minimum spanning tree

### Key Concepts

1. A brute force algorithm always finds the ideal solution but can be impractical whereas a greedy algorithm is efficient but usually does not lead to the ideal solution.
2. A Hamilton cycle of lowest weight is a solution to the traveling salesperson problem.
3. The brute force method finds a Hamilton cycle of lowest weight in a complete graph.
4. The nearest neighbor method is a greedy algorithm that finds a Hamilton cycle of relatively low weight in a complete graph.

### Videos

1. The Problem in
2. Spanning Trees in Graph Theory
3. Use Kruskal's Algorithm to Find Minimum Spanning Trees in Graph Theory

### Formulas

1. The number of edges in a tree graph with  vertices is . A connected graph with n vertices and  edges is a tree graph.

### Projects

Everyone Gets a Turn! – Graph Colorings
Let’s put your knowledge of graph colorings to work! Your task is to plan a field day following these steps.
1. Select between seven and ten activities for your field day. You can look online for ideas.
2. Create a survey asking for the participants to select the three to five events in which they would most like to participate. Survey between seven and ten people.
3. Use the results of your survey to create a graph in which each vertex represents one of the events. A pair of vertices will be adjacent if there is at least one participant who would like to participate in both events.
4. Find a minimum coloring for the graph. Explain how you found it and how you know the chromatic number of the graph.
5. Use your solution to part d to determine the minimum number of timeslots you must use to ensure that everyone has the opportunity to participate in their top three events.
6. Find the complement of the graph you created. Explain what the edges in this graph represent.
A Beautiful Day in the Neighborhood – Euler Circuits
Let’s apply what you have learned to the community in which you live. Using resources such as your county’s property appraiser’s website, create a detailed graph of your neighborhood in which vertices represent turns and intersections. Represent a large enough part of your community to include no fewer than 10 intersections or turns. Then use your graph to answer the following questions.
1. Label the edges of your graph.
2. Determine if your graph is Eulerian. Explain how you know. If it is not, eulerize it.
3. Find an Euler circuit for your graph. Give the sequence of vertices that you found.
4. What does the Euler circuit you found in part c represent for your community?
5. Describe an application for which this Euler circuit might be used.
Dream Vacation – Hamilton Cycles and Paths
Where in the world would you like to travel most: the Eiffel Tower in Paris, a Broadway musical in New York city, a bike tour of Amsterdam, the Tenerife whale and dolphin cruises in the Canary Islands, the Giza Pyramid in Cairo, or maybe the Jokhang Temple in Tibet? Let's plan your dream vacation!
1. Which four destinations are at the top of your bucket list?
2. Draw a complete weighted graph with five vertices representing the four destinations and your home city, and the weights representing the cost of travel between cities.
3. Use a website (such as Travelocity) to find the best airfare between each pair of cities. List the airlines and flight numbers along with the prices. Include cost for ground transportation from the nearest airport if there is no airport at the destination you want to visit.
4. Use the nearest neighbor algorithm to find a Hamilton cycle of low weight beginning and ending in your hometown. What is the weight of this circuit and what does it represent?
5. Use the brute force method to find a Hamilton cycle of lowest weight beginning and ending in your hometown. What is the weight of this circuit? Is it the same or different from the weight of the Hamilton cycle you found in Exercise 4?
6. Suppose that instead of returning home, you planned to move to your favorite location on the list, but you wanted to stop at the other three destinations once along the way. Where would you move? List all Hamilton paths between your hometown and your favorite location.
7. Find the weights of all the Hamilton paths you found in Exercise 6.

### Chapter Review

### Graph Basics

### Graph Structures

### Comparing Graphs

### Navigating Graphs

### Euler Circuits

### Euler Trails

### Hamilton Cycles

### Hamilton Paths

### Traveling Salesperson Problem

### Trees

### Chapter Test


# Math and...

## Introduction

Where do we find math around us? Math can be found in areas that are expected and sometimes in areas that are surprising. There are many ways that mathematical concepts, such as those in this text, are infused in the world around us. In this chapter, we will explore a sampling of five distinct areas from everyday life where math’s impact plays a meaningful role.
Math's impact on art can be found in numerical relationships that are known to create or enhance beauty. The Fibonacci numbers are one mathematical example that can be found in nature such as in petal count of a rose. On a different note, a mathematical exploration can aid in making a convincing argument on how we can positively impact our environment. Whether looking at the choices of a single individual or the larger impact offered from a collaborative effort, there are measurable responses to positively address climate change. Turning to medicine, which has been a topic of global importance in recent years, we will explore how math is used to determine drug dosage rates and test the validity of a vaccine. Switching back to items of aesthetic nature, we will examine some foundational components of music which, like art, brings beauty and joy to our lives. Finally, we will explore some ways that math is used in sports to predict future performance and analyze tournaments styles.


# Math and...

## Math and Art

### Learning Objectives

After completing this section, you should be able to:
1. Identify and describe the golden ratio.
2. Identify and describe the Fibonacci sequence and its application to nature.
3. Apply the golden ratio and the Fibonacci sequence relationship.
4. Identify and compute golden rectangles.
Art is the expression or application of human creative skill and imagination, typically in a visual form such as painting or sculpture, producing works to be appreciated primarily for their beauty or emotional power.
Oxford Dictionary
Art, like other disciplines, is an area that combines talent and experience with education. While not everyone considers themself skilled at creating art, there are mathematical relationships commonly found in artistic masterpieces that drive what is considered attractive to the eye. Nature is full of examples of these mathematical relationships.
Enroll in a cake decorating class and, when you learn how to create flowers out of icing, you will likely be directed as to the number of petals to use. Depending on the desired size of a rose flower, the recommendation for the number of petals to use is commonly 5, 8, or 13 petals. If learning to draw portraits, you may be surprised to learn that eyes are approximately halfway between the top of a person’s head and their chin. Studying architecture, we find examples of buildings that contain golden rectangles and ratios that add to the beautifying of the design. The Parthenon (), which was built around 400 BC, as well as modern-day structures such the Washington Monument are two examples containing these relationships. These seemingly unrelated examples and many more highlight mathematical relationships that we associate with beauty in artistic form.

### Golden Ratio

The golden ratio, also known as the golden proportion, is a ratio aspect that can be found in beauty from nature to human anatomy as well as in golden rectangles that are commonly found in building structures. The golden ratio is expressed in nature from plants to creatures such as the starfish, honeybees, seashells, and more. It is commonly noted by the Greek letter ϕ (pronounced “fee”). , which has a decimal value approximately equal to 1.618.
Consider : Note how the building is balanced in dimension and has a natural shape. The overall structure does not appear as if it is too wide or too tall in comparison to the other dimensions.
The golden ratio has been used by artists through the years and can be found in art dating back to 3000 BC. Leonardo da Vinci is considered one of the artists who mastered the mathematics of the golden ratio, which is prevalent in his artwork such as Virtuvian Man  (). This famous masterpiece highlights the golden ratio in the proportions of an ideal body shape.
The golden ratio is approximated in several physical measurements of the human body and parts exhibiting the golden ratio are simply called golden. The ratio of a person’s height to the length from their belly button to the floor is ϕ or approximately 1.618. The bones in our fingers (excluding the thumb), are golden as they form a ratio that approximates ϕ. The human face also includes several ratios and those faces that are considered attractive commonly exhibit golden ratios.

### Fibonacci Sequence and Application to Nature

The Fibonacci sequence can be found occurring naturally in a wide array of elements in our environment from the number of petals on a rose flower to the spirals on a pine cone to the spines on a head of lettuce and more. The Fibonacci sequence can be found in artistic renderings of nature to develop aesthetically pleasing and realistic artistic creations such as in sculptures, paintings, landscape, building design, and more. It is the sequence of numbers beginning with 1, 1, and each subsequent term is the sum of the previous two terms in the sequence (1, 1, 2, 3, 5, 8, 13, …).
The petal counts on some flowers are represented in the Fibonacci sequence. A daisy is sometimes associated with plucking petals to answer the question “They love me, they love me not.” Interestingly, a daisy found growing wild typically contains 13, 21, or 34 petals and it is noted that these numbers are part of the Fibonacci sequence. The number of petals aligns with the spirals in the flower family.

### Golden Ratio and the Fibonacci Sequence Relationship

Mathematicians for years have explored patterns and applications to the world around us and continue to do so today. One such pattern can be found in ratios of two adjacent terms of the Fibonacci sequence.
Recall that the Fibonacci sequence = 1, 1, 3, 5, 8, 13,… with 5 and 8 being one example of adjacent terms. When computing the ratio of the larger number to the preceding number such as 8/5 or 13/8, it is fascinating to find the golden ratio emerge. As larger numbers from the Fibonacci sequence are utilized in the ratio, the value more closely approaches ϕ, the golden ratio.

### Golden Rectangles

Turning our attention to man-made elements, the golden ratio can be found in architecture and artwork dating back to the ancient pyramids in Egypt () to modern-day buildings such as the UN headquarters. The ancient Greeks used golden rectangles—any rectangles where the ratio of the length to the width is the golden ratio—to create aesthetically pleasing as well as solid structures, with examples of the golden rectangle often being used multiple times in the same building such as the Parthenon, which is shown in . Golden rectangles can be found in twentieth-century buildings as well, such as the Washington Monument.
Looking at another man-made element, artists paintings often contain golden rectangles. Well-known paintings such as Leonardo da Vinci’s The Last Supper and the Vitruvian Man contain multiple golden rectangles as do many of da Vinci’s masterpieces.
Whether framing a painting or designing a building, the golden rectangle has been widely utilized by artists and are considered to be the most visually pleasing rectangles.

### Check Your Understanding

### Key Terms

1. golden ratio
2. ϕ
3. Fibonacci sequence
4. golden rectangle

### Key Concepts

1. The golden ratio, ϕ, can be found in nature, and the relationship is often associated with beauty and balance.
2. The Fibonacci sequence reflects a pattern of numbers that can be found in various places in nature. The sequence can be used to predict other values that follow the Fibonacci pattern.
3. State some naturally occurring applications of the Fibonacci sequence.
4. State some naturally occurring applications of the golden ratio.
5. Determine if a rectangle is golden.
6. State some artistic applications of the golden rectangle.


# Math and...

## Math and the Environment

### Learning Objectives

After completing this section, you should be able to:
1. Compute how conserving water can positively impact climate change.
2. Discuss the history of solar energy.
3. Compute power needs for common devices in a home.
4. Explore advantages of solar power as it applies to home use.
Climate change and emissions management have been debated topics in recent years. However, more and more people are recognizing the impacts that have resulted in temperature changes and are seeking timely and effective action. The World Meteorological Organization shared in a June 2021 publication that “2021 is a make-or-break year for climate action, with the window to prevent the worst impacts of climate change—which include ever more frequent more intense droughts, floods and storms—closing rapidly.” The problem no longer belongs to a few countries or regions but rather is a worldwide concern measured with increasing temperatures leading to decreased glacier coverage and resulting rise in sea levels.
The good news is, there are small steps that each of us can do that collectively can positively impact climate change.

### Making a Positive Impact on Climate Change—Water Usage

Our use of water is one element that impacts climate change. Having access to clean, potable water is critical for not only our health but also for the health of our ecosystem. About 1 out of 10 people on our planet do not have easy access to clean water to drink. As each of us conserves water, we prolong the life span of fresh water from our lakes and rivers and also reduce the impact on sewer systems and drainage in our communities. Additionally, as we conserve water, we also conserve electricity that is used to bring water to and in our homes. So, what can we do to help conserve water?

### History of Solar Energy

In the mid-1800s, Willoughby Smith discovered photoconductive responsiveness in selenium. Shortly thereafter, William Grylls Adams and Richard Evans Day discovery that selenium can produce electricity if exposed to the sun was a major breakthrough. Less than 10 years later, Charles Fritts invented the first solar cells using selenium. Jumping a mere 100 years later, Bell Labs in the United States produced the first practical photovoltaic cells in the mid-1950s and developed versions used to power satellites in the same decade.
Solar panel use has exploded in recent decades and is now used by residences, organizations, businesses, and government buildings such as the White House, space to power satellites, and various methods of transportation. One reason for the expansion is a continuing drop in cost combined with an increase in performance and durability. In the mid-1950s, the cost of a solar panel was around $300 per watt capability. Twenty years later, the cost was a third of the 1950s’ cost. Currently, solar panel cost has dropped to less than $1 per watt while decreasing in size as well as increasing in longevity. The dropping price and improved performance has moved solar to a modest investment that can pay for itself in less than half the time of systems from 15 years ago.

### Compute Power Needs for Common Home Devices

A kilowatt (kW) is 1,000 watts (W). A kilowatt-hour (kWh) is a measurement of energy use, which is the amount of energy used by a 1,000-watt device to run for an hour. Using the definition of a kilowatt-hour, to calculate how long it would take to consume 1 kWh of power, we divide 1,000 by the watts use of a device.
For example, a 75 W bulb would take  to use 1 kW of power.

### Solar Advantages

There are multiple advantages that solar power can offer us today including reducing greenhouse gas and CO2 emissions, powering vehicles, reducing water pollution, reducing strain on limited supply of other power options such as fossil fuels. We will look further at reducing greenhouse gas and CO2 emissions.
Any gas that prevents infrared radiation from escaping Earth's atmosphere is a greenhouse gas. There are 24 currently identified greenhouse gases of which carbon dioxide is one. When measuring the impact of any of the greenhouse gases, the measurements are given in units of carbon dioxide emissions. For this reason, greenhouse gas and carbon dioxide have become interchangeable in discussions.

### Check Your Understanding

### Key Terms

1. greenhouse gas
2. CO2 emissions
3. watt
4. kilowatt (kW)

### Key Concepts

1. Recognize how water conservation by one person, family, community, or nation can positively impact the world’s freshwater supply.
2. Recall components from the history of solar use by mankind.
3. Calculate electrical demand given watts.
4. Recognize advantages of residential solar power.

### Formulas


# Math and...

## Math and Medicine

### Learning Objectives

After completing this section, you should be able to:
1. Compute the mathematical factors utilized in concentrations/dosages of drugs.
2. Describe the history of validating effectiveness of a new drug.
3. Describe how mathematical modeling is used to track the spread of a virus.
The pandemic that rocked the world starting in 2020 turned attention to finding a cure for the Covid-19 strain into a world race and dominated conversations from major news channels to households around the globe. News reports decreeing the number of new cases and deaths locally as well as around the world were part of the daily news for over a year and progress on vaccines soon followed. How was a vaccine able to be found so quickly? Is the vaccine safe? Is the vaccine effective? These and other questions have been raised through communities near and far and some remain debatable. However, we can educate ourselves on the foundations of these discussions and be more equipped to analyze new information related to these questions as it becomes available.

### Concentrations and Dosages of Drugs

Consider any drug and the recommended dosage varies based on several factors such as age, weight, and degree of illness of a person. Hospitals and medical dispensaries do not stock every possible needed concentration of medicines. Drugs that are delivered in liquid form for intravenous (IV) methods in particular can be easily adjusted to meet the needs of a patient. Whether administering anesthesia prior to an operation or administering a vaccine, calculation of the concentration of a drug is needed to ensure the desired amount of medicine is delivered.
The formula to determine the volume needed of a drug in liquid form is a relatively simple formula. The volume needed is calculated based on the required dosage of the drug with respect to the concentration of the drug. For drugs in liquid form, the concentration is noted as the amount of the drug per the volume of the solution that the drug is suspended in which is commonly measured in g/mL or mg/mL.
Suppose a doctor writes a prescription for 6 mg of a drug, which a nurse calculates when retrieving the needed prescription from their secure pharmaceutical storage space. On the shelves, the drug is available in liquid form as 2 mg per mL. This means that 1 mg of the drug is found in 0.5 mL of the solution. Multiplying 6 mg by 0.5 mL yields 3 mL, which is the volume of the prescription per single dose.
A common calculation for the weight of a liquid drug is measured in grams of a drug per 100 mL of solution and is also called the percentage weight by volume measurement and labeled as % w/v or simply w/v.
Suppose you visit your doctor with symptoms of an upset stomach and unrelenting heartburn. One possible recourse is sodium bicarbonate, which aids in reducing stomach acid.

### Validating Effectiveness of a New Vaccine

The process to develop a new vaccine and be able to offer it to the public typically takes 10 to 15 years. In the United States, the system typically involves both public and private participation in a process. During the 1900s, several vaccines were successfully developed, including the following: polio vaccine in the 1950s and chickenpox vaccine in the 1990s. Both of these vaccines took years to be developed, tested, and available to the public. Knowing the typical timeline for a vaccine to move from development to administration, it is not surprising that some people wondered how a vaccine for Covid-19 was released in less than a year’s time.
Lesser known is that research on coronavirus vaccines has been in process for approximately 10 years. Back in 2012, concern over the Middle Eastern respiratory syndrome (MERS) broke out and scientists from all over the world began working on researching coronaviruses and how to combat them. It was discovered that the foundation for the virus is a spike protein, which, when delivered as part of a vaccine, causes the human body to generate antibodies and is the platform for coronavirus vaccines.
When the Covid-19 pandemic broke out, Operation Warp Speed, fueled by the U.S. federal government and private sector, poured unprecedented human resources into applying the previous 10 years of research and development into targeting a specific vaccine for the Covid-19 strain.

### Mathematical Modeling to Track the Spread of a Vaccine

With a large number of people receiving a Covid-19 vaccine, the concern at this time is how to create an affordable vaccine to reach people all over the world. If a world solution is not found, those without access to a vaccine will serve as incubators to variants that might be resistant to the existing vaccines.
As we work to vaccinate the world, attention continues with tracking the spread of the Covid-19 and its multiple variants. Mathematical modeling is the process of creating a representation of the behavior of a system using mathematical language. Digital mathematical modeling plays a key role in analyzing the vast amounts of data reported from a variety of sources such as hospitals and apps on cell phones.
When attempting to represent an observed quantitative data set, mathematical models can aid in finding patterns and concentrations as well as aid in predicting growth or decline of the system. Mathematical models can also be useful to determine strengths and vulnerabilities of a system, which can be helpful in arresting the spread of a virus.
The chapter on Graph Theory explores one such method of mathematical modeling using paths and circuits. Cell phones have been helpful in tracking the spread of the Covid-19 virus using apps regulated by regional government public health authorities to collect data on the network of people exposed to an individual who tests positive for the Covid-19 virus.
Consider the following graph ():
At the center of the graph, we find Alyssa, whom we will consider positive for a virus. Utilizing the technology of phone apps voluntarily installed on each phone of the individuals in the graph, tracking of the spread of the virus among the 6 individuals that Alyssa had direct contact with can be implemented, namely Suad, Rocio, Braeden, Soren, and Sandra.
Let’s look at José’s exposure risk as it relates to Alyssa. There are multiple paths connecting José with Alyssa. One path includes the following individuals: José to Mikaela to Nate to Sandra to Alyssa. This path contains a length of 4 units, or people, in the contact tracing line. There are 2 more paths connecting José to Alyssa. A second path of the same length consists of José to Lucia to Rocio to Braeden to Alyssa. Path 3 is the shortest and consists of José to Lucia to Rocio to Alyssa. Tracking the spread of positive cases in the line between Alyssa and José aids in monitoring the spread of the infection.
Now consider the complexity of tracking a pandemic across the nation. Graphs such as the one above are not practical to be drawn on paper but can be managed by computer programs capable of computing large volumes of data. In fact, a computer-generated mathematical model of contact tracing would look more like a sphere with paths on the exterior as well as on the interior. Mathematical modeling of contact tracing is complex and feasible through the use of technology.

### Check Your Understanding

### Key Terms

1. concentrations/dosages of drugs
2. mathematical modeling

### Key Concepts

1. Compute volumes of prescription drugs in liquid and pill form.
2. Validate the effectiveness of a new drug.
3. Mathematical modeling can be used to describe and track the spread of a virus.

### Formula

.


# Math and...

## Math and Music

### Learning Objectives

After completing this section, you should be able to:
1. Describe the basics of frequency related to sound.
2. Describe the basics of pitch as it relates to music.
3. Describe and evaluate musical notes, half-steps, whole steps, and octaves.
4. Describe and find frequencies of octaves.
“The world’s most famous and popular language is music.”
Psy, South Korean singer, rapper, songwriter, and record producer
Imagine a world without music and many of us would struggle to fill the void. Music uplifts, inspires, heals, and generally adds dimension to virtually every aspect of our lives. But what is music? For some it is a song; for others it may be the sounds of birds or the rhythmic sound of drumming or a myriad of other sounds. Whatever you consider music, it is all around us and is an integral part of our lives. “Music can raise someone’s mood, get them excited, or make them calm and relaxed. Music also—and this is important—allows us to feel nearly or possibly all emotions that we experience in our lives. The possibilities are endless” (Galindo, 2009).
What music you listen to can impact your mood and emotions. In similar fashion, the music we choose can often tell those around us something about our current moods and emotions. Consider the music you may have been listening to as you today or even as you are reading this text. What cues to your mood do your music selections share? Albert Einstein is quoted as saying, “If I were not a physicist, I would probably be a musician. I often think in music. I live my daydreams in music. I see my life in terms of music.” What clues do your recent music choices say about your mood or how your day is going?

### Basics of Frequency as It Relates to Sound

Every sound is created by an object vibrating and these vibrations travel in waves that are captured by our ears. Some vibrations we may be able to see, such as a plucked guitar string moving, whereas other vibrations we may not be able to see, such as the sound created when we hold our breath when accidentally dropping our cell phone on a hard floor. We don’t see the vibrations of our cell phone hitting the floor; however, any audible sound created in the fall is the result of vibrations in the form of sound waves, which can be pictured similarly to waves moving through the ocean.
The waves of sounds each have a frequency, or rate of vibration of sound waves, that measures the number of waves completed in a single second and are measured in hertz (Hz; one Hz is one cycle per second). Louder sounds have stronger vibrations or are created closer to our ear. The further an ear is from the source of the sound, the quieter the sound will appear.
Sounds range in frequency from 16 Hz to ultrasonic values, with humans able to hear sounds in a frequency range of about 20 Hz to 20,000 Hz. Adults lose the ability to hear the upper end of the range and typically top out in the ability to hear in a frequency of 15,000–17,000 Hz. Sounds with a frequency above 17,000 Hz are less likely to be heard by adults while still being audible to children.
While frequency plays a key role in audible sounds, so too does the sound level, which can be measured in decibels (dB), which are the units of measure for the intensity of a sound or the degree of loudness. As a sound level increases, the decibel level increases.
A person with average hearing can hear sounds down to 0 dB. Those with exceptionally good hearing can hear even quieter sounds, down to approximately –5 dB. The following table includes sample sounds with their related decibel values.

### Basics of Pitch

When considering the various sound levels the human ear can hear, the ear perceives sound both from the frequency level and the pitch of a sound. The quality of the sound is referred to as pitch, the tonal quality of a sound and how high or low the tone. Sounds with a high frequency have a high pitch, such as 900 Hz, and sounds with a low pitch have a low frequency, such as 50 Hz.
Let’s take a look at frequency and pitch using a string instrument such as a guitar or piano. When a string is plucked on a guitar or a key is played on a piano, the related string vibrates at a frequency that is related to the length and thickness of the string. The frequency is measurable and has a singular value. The pitch of the note played is open for interpretation, as the pitch is a function of personal opinion.

### Note Values, Half-Steps, Whole Steps, and Octaves

“There are not more than five musical notes, yet the combinations of these five give rise to more melodies than can ever be heard.”
Sun Tzu, Chinese strategist
Moving our exploration to note values, the frequency of all notes is well defined by a specific and unique frequency for each note that is measurable. We will explore keys on a keyboard to discuss notes that have the same relationships with any instrument or musical piece.
Let’s look at . The white keys are labeled with the letters A–G and the photo begins with middle C, which can be found in the middle of a keyboard. This labeling of the keys repeats across an entire keyboard and keys to the right have a higher pitch and frequency than keys to the left. Each of the keys correlates to a musical note.
Movement up or down between any two consecutive keys (black and white) or notes constitutes a half-step. Movement of one half-step sometimes involves a sharp (#) or a flat (♭) symbol. For example, D# is one half-step above D and D♭ is one half-step below D. Note that this is not always true as one half-step above B is C, and one half-step below F is E. In similar fashion, a whole step is movement up or down between any two half-steps on a keyboard.
You may have noticed that there are eight letters of the alphabet used to label notes. Selecting any one note and counting up 12 half-steps you will find that the numbering for notes begins at the same value as you started from. This collection of 12 consecutive half-notes is called an octave and is a basic foundational component in music theory.

### Frequencies of Octaves

Notes that are one octave apart have the same name and are related in frequency values. Given the frequency of any note, the frequency of same note one octave higher is doubled and this pattern continues as you move up and down the notes on a keyboard or any other musical instrument. Song writers and singers use this knowledge to change the pitch of a note up or down to align with a person’s vocal range. Regardless of which C is played or sung, the pitch is the same and the frequency is related by a power or two.
Labeled keys on a keyboard are numbered for ease in identification. For example, middle C is labeled as C4 on a full keyboard as it is the fourth C from the left in a set of eight notes. The frequency of C4 is 262 Hz, rounded to the nearest whole number.
We have explored some basics components of frequency, pitch, note relationships, and octaves, which are building blocks of music. It may be exciting to learn that the mathematical relationships found in music are vast and grow in complexity beyond the math commonly studied in high school.

### Check Your Understanding

### Key Terms

1. frequency
2. pitch
3. Hertz
4. decibel
5. half-step
6. whole step
7. flat
8. sharp
9. octave

### Key Concepts

1. As frequency of a sound increases, the pitch of the sound increases.
2. Hertz is a unit of measurement for frequency.
3. Decibel is a unit of measurement for the intensity of sound.
4. Half-steps and whole-steps describe one type of movement between two notes on a keyboard.
5. Octaves are a collection of any 12 consecutive notes, which is a foundation in music theory.


# Math and...

## Math and Sports

### Learning Objectives

After completing this section, you should be able to:
1. Describe why data analytics (statistics) is crucial to advance a team’s success.
2. Describe single round-robin method of tournaments.
3. Describe single-elimination method of tournaments.
4. Explore math in baseball, fantasy football, hockey, and soccer (projects at the end of the section).
Sports are big business and entertainment around the world. In the United States alone, the revenue from professional sports is projected to bring in over $77 billion, which includes admission ticket costs, merchandise, media coverage access rights, and advertising. So, whether or not you enjoy watching professional sports, you probably know someone who does. Some celebrities compete to be part of half-time shows and large companies vie for commercial spots that are costly but reach a staggering number of viewers, some who only watch the half-time shows and advertisements.

### Data Analytics (Statistics) Is Crucial to Advance a Team’s Success

Analyzing the vast data that today’s world has amassed to find patterns and to make predictions for future results has created a degree field for data analytics at many colleges, which is in high demand in places that might surprise you. One such place is in sports, where being able to analyze the available data on your team’s players, potential recruits, opposing team strategies, and opposing players can be paramount to your team’s success.
Hollywood turned the notion of using data analytics into a major motion picture back in 2011 with the release of Moneyball, starring Brad Pitt, which grossed over $110 million. The critically acclaimed movie, based on a true story as shared in a book by Michael Lewis, follows the story of a general manager for the Oakland Athletics who used data analytics to take a team comprised of relatively unheard of players to ultimately win the American League West title in a year’s time. The win caught the eye of other team managers and owners, which started an avalanche of other teams digging into the data of players and teams.
In today’s world of sports, a team has multiple positions utilizing data analytics from road scouts who evaluate a potential recruit’s skills and potential to the ultimate position of general manager who is typically the highest-paid (non-player) employee with the exception of the coaches. Being able to understand and evaluate the available data is big business and is a highly sought after skill set. In college and professional sports, it is no longer sufficient to have a strong playbook and great players. The science to winning is in understanding the math of the data and using it to propel your team to excelling.

### Single Round-Robin Tournaments

A common tournament style is single round-robin tournaments (), where each team or opponent plays every other team or opponent, and the champion is determined by the team that wins the most games. Ties are possible and are resolved based on league rules.
An advantage of the round-robin tournament style is that no one team has the advantage of seeding, which eliminates some teams from playing against each other based on rank of their prior performance. Rather, each team plays every other team, providing equal opportunity to triumph over each team. In this sense, round-robin tournaments are deemed the fairest tournament style.
One hindrance to employing a round-robin-style tournament is the potential for the number of games involved in tournament play to determine a winner. Determining the number of games can be found easily using a formula which, as we will see, can quickly grow in the number of games required for a single round-robin tournament.
As the examples show, single round-robin tournament play can quickly grow in the number of games required to determine a champion. As such, some tournaments elect to employ variations of single round-robin tournament play as well as other tournament styles such as elimination tournaments.

### Single-Elimination Tournaments

When desiring a more efficient tournament style to determine a champion, one option is single-elimination tournaments (), where teams are paired up and the winner advances to the next round of play. The losing team is defeated from tournament play and does not advance in the tournament, although some leagues offer consolation matches.
A single-elimination tournament offers an advantage over single round-robin tournament style of play in the number of games needed to complete the tournament. As you can see, in comparing the number of games in a single round-robin tournament in  with the number of games in single-elimination tournament as shown in , the number of games required for single round-robin can quickly become unmanageable to schedule.
There are modifications to both the round-robin and elimination tournament styles such as double round-robin and double-elimination tournaments. Next time you observe a college or professional sporting event, see if you can determine the tournament style of play.

### Check Your Understanding

### Key Terms

1. data analytics
2. seeding

### Key Concepts

1. Describe how a round-robin tournament is organized.
2. Compute the number of games played in a round-robin tournament.
3. Describe how a single-elimination tournament is organized.
4. Compute the number of games played in a single-elimination tournament.

### Formulas

Number of games in a single round-robin tournament with  teams is .
Number of games in a single-elimination tournament with  teams is .

### project

### Lucas Sequence and Fibonacci Sequence

The Lucas numbers bear some similarity to the Fibonacci numbers and exhibit a stronger link to the golden ratio. Edouard Lucas is credited with naming the Fibonacci numbers and the Lucas numbers were so named in his honor. The Lucas numbers play a role in finding prime numbers that are utilized in encrypting data for actions such as using your debit card to obtain money at a cash machine or when making a credit card purchase for point of sale as well as when shopping online.
Complete the following questions to explore numbers in the Lucas sequence as well as their relationships to the numbers in the Fibonacci sequence.

### Solar Array for a Residence

One of the first steps in adding solar to a residence is determining the size of a system to achieve the desired output. In this project, we will explore the solar needs of a residence and estimate needs of a solar array to supply electrical output to meet various percentages of electrical need.
Step 1: Obtain an electric bill from your apartment/home. Find the average monthly or yearly usage if listed or call the electric company to inquire. If an electric bill is not available, use the Internet to find an average monthly or yearly electric usage for your area.
Step 2: Determine a daily and hourly usage. Divide the average monthly usage by 30 or the yearly average by 365. Divide again by 24 to calculate an average hourly electric usage, which will yield the average kilowatt-hours for how much electrical power your is being utilized in an hour.
Step 3: Multiply your average hourly use (kilowatts) by 1,000 to convert to watts.
Step 4: Use the Internet to determine the average daily peak hours of sunlight where you live.
Step 5: Divide your average hourly watts (Step 3) by the average daily peak hours (Step 4) to calculate the average energy needed for a solar array to produce every hour.
Step 6: Determine the average energy needed in a solar array per hour to meet each of the following:

Step 7: Using the values computed in Step 6, compute the residential savings based on an average cost of 12 cents per watt.

### Vaccine Validation

Validation of vaccines is a topic that exploded in the news when the Covid-19 pandemic spread across the world. As governments and organizations looked for a vaccine to curb the spread and minimize the severity of infection, concern was expressed by some for what appeared to be a quick discovery for a Covid-19 vaccine.
Conduct an Internet search to explore the following questions. Pay special attention to the sources you select to ensure that they are credible sources.

### Frequency and Ultrasonic Sounds

Ultrasonic sounds have been utilized for a variety of reasons, from purportedly repelling rodents and other animals as well as a variety of other applications. Using an Internet search, complete the following questions to explore some of these applications and examine the validity of various claims.

### Repelling Insects, Rodents, and Small Animals

Some radio stations purport to play a high pitch sound dually with their music to aid in deterring insects and other annoying bugs to aid in providing a bug-reduced listening environment. To deter small rodents, some products claim to emit ultrasonic sounds that drive away mice and other similar pests.

### Disbursing Teenagers

Some business owners and communities have turned to products such as the “mosquito” sonic deterrent device to discourage groups of teenagers from loitering around storefronts and community landmarks, citing a public nuisance issue and public safety concerns.

### Jewelry Cleaner

Use of pastes and liquid chemicals to clean jewelry can be harsh on stones as well as metals. So how can we safely obtain the sparkling clean look at home that jewelry stores provide? Some would say the answer is to use an ultrasonic jewelry cleaner, but do these really work?

### Specialized Ringtones

As the use of cell phones has become commonplace and families grow towards each member having their own cell phone, specialized ringtones have become popular and can aid in identifying who is calling just by the ringtone.
Ever hear of ringtones that can be heard by teens but often not their teachers? The banning of cell phone use by K–12 students during class time as been implemented across a wide array of schools and some students have purportedly found ways to get around teachers hearing a cell phone ring through the use of ultrasonic ringtones.

### Streaming Services and Math

With the ability to stream music virtually anywhere you are, it is not surprising that Google Play Music, Apple Music, and a slew of other companies such as Spotify, Amazon Music, YouTube Music, Sound Cloud, Pandora, Deezer Music, Tidal, Napster, and Bandcamp have invested heavily to bring streaming service to users worldwide. Streaming services have expanded to offer virtually every genre of music with vast libraries to meet diverse user requests.
Considering all of the choices available for streaming music, there is a wide array of options for subscribing. Conduct an Internet research to review your current streaming choices, if any, and evaluate competitors’ products.

### Math and Baseball

Baseball is known to have one of the largest pools of statistics related to the game and its players. Managers, coaches, and pitchers study the statistics of the players on opposing teams to give their team an edge by knowing what pitches to throw for the best probability to be missed by a batter. In similar fashion, batters study pitchers’ statistics to learn a pitcher’s strength and how to predict what a pitcher will throw and how to best hit against a pitcher.
The three primary baseball statistics are batting average, home runs, and runs batted in (RBIs), which are the components of the title of Triple Crown winner that is awarded to players who dominate in these three areas. However, there is a wealth of other statistics to evaluate when studying the performance of a player.
Conduct an Internet search to research statistics and how they are calculated in the following categories:

### Batting Statistics

1. There are about 30 batting statistics. Select a minimum of 10 batting statistics. Compose an organized list including the name of the statistic, abbreviation, explanation of what it represents, as well as how it is calculated.
    As an example: AB/HR represents at bats per home run and is calculated by the number of times a player is at bat divided by home runs.

### Pitching Statistics

1. There are about 40 pitching statistics. Select a minimum of 10 pitching statistics. Compose an organized list including the name of the statistic, abbreviation, explanation of what it represents, as well as how it is calculated.
    As an example: K/9 represents strikeouts per nine innings and is calculated by the number of strikeouts times nine divided by the number of innings pitched.

### Fielding Statistics

1. There are around 10 fielding statistics. Select a minimum of five fielding statistics. Compose an organized list including the name of the statistic, abbreviation, explanation of what it represents, as well as how it is calculated.
    As an example: FP represents fielding percentage is calculated by the number of total plays divided by the number of total chances.

### Overall

1. Select a player from recent years to evaluate. The player can be one that you have followed, one from a favorite team, or any current player. Find the statistics shared in Questions 1–3 to use in evaluating the potential strengths and weaknesses of the player. Write a short paragraph analyzing your selected player, supported by the statistics from the answers to Questions 1–3.

### Math and Fantasy Football

Fantasy football offers spectators an added dimension to football season with a competitive math-based game where the active components are real-life players in the current season. For clarity in this exercise, the actual fantasy football players will be denoted as FFP and actual professional team members will be denoted as players.
While some fantasy football leagues have slightly different setups or scoring systems, most share some common elements.
Often using a lottery system to determine who picks first, second, and so on, FFPs select 15 current players to comprise their personal fantasy football team. The players selected can be from any professional teams and a FFP can utilize any team recognized by their league. FFPs can elect to keep the same players on their team for the whole league play or trade for any player not selected by another FFP in their league.
At the start of each week during football season, each fantasy football player selects their roster of actual players to comprise their roster of starting players. Typically, a starting roster consists of the following players:

As actual professional games are played, points are tallied based on your league’s scoring system. The points the team members on your starting roster make during the week are computed and whichever FFP has the highest score for the week wins that week.
The FFPs with the best records of wins versus losses enters fantasy football playoffs to determine the ultimate league champion and collects the pot.
The above overview of fantasy football describes the basic game play. The fun comes in understanding and analyzing the math behind the scoring.

### Math and Hockey

Hockey is full of math from obvious components such as scoring and statistics to the shape of the rink and the angles involved in puck movement.
Collegiate and professional hockey games are 60 minutes long and are divided into three periods of 20 (60/3) minutes each. At any one time, there are five players and one goalie on the ice for each team. If a player is called on a penalty and is placed in the penalty box, that team now has four players, which is 20% less players on the ice competing against five opponents. In some instances, a team may have two players in the penalty box at one time, resulting in three players, or 40% less players on the ice compared to a full team. Being one player down for a 2-minute penalty or potentially 5 minutes for a major penalty leads to an imbalance on the ice and calls for a quick change of offense and defense strategy.

### Rink Composition—North American

An ice rink is comprised of various geometrical shapes, each with precise dimensions.

### Statistics

Using an Internet search, select two top hockey players from the same league to answer the following questions:
1. Write a paragraph sharing a minimum of five statistics for each player you have selected. Describe how each of the statistics are calculated and what each statistic means.
2. Write a paragraph comparing the two players and determine who you believe is the better player. Support your choice.

### Scoring

The basics of scoring in ice hockey is simple, the team with the most goals is the winner. But, how to score the most goals involves much math!

### Math and Soccer

As the world’s most popular sport, you’ll be excited to confirm that soccer is full of mathematics ranging from scoring and statistics to footwork, angles, and field shape.
Soccer requires understanding of mathematical concepts and equations as well as skill, fitness, and game knowledge. One such example is angles, which you all will remember from your geometry class. While players are not carrying protractors and measuring angles during play, mental calculation of angles is a constant in any successful player’s thinking. A goalie is not physically able to cover the entire open net region and a player must calculate an angle to kick the ball consistent with the net opening while predicting the ability of the goalie to stop the ball from entering the net.

Using an Internet search, select two top soccer players from the same league to answer the following questions:

### Chapter Review

### Section 13.1 Math and Art

### Section 13.2 Math and the Environment

### Section 13.3 Math and Medicine

### Section 13.4 Math and Music

### Section 13.5 Math and Sports

### Chapter Test


# Introduction

## What is MATLAB?

MATLAB stands for MATrix LABoratory (see  wikipedia) and is a commercial software application written by The MathWorks, Inc. When you first use MATLAB, you can think of it as a glorified calculator allowing you to perform engineering calculations and plot data. However, MATLAB is more than an advanced scientific calculator, for example MATLAB's sophisticated numerical computation environment also allows us to analyze data, simulate engineering systems, document and share our code with others.

### Why Use MATLAB?

MATLAB has become a defacto standard in many fields of engineering and science. Even a casual exploration of MATLAB should unveil its computational power however a closer look at MATLAB's graphics and data analysis tools as well as interaction with other applications and programing languages prove why MATLAB is a very strong application for technical computing.

The standard MATLAB installation includes graphics features to visualize engineering and scientific data in 2-D and 3-D plots. We can interactivity build graphs and generate MATLAB command output that can be saved for use in the future. The saved-instructions can be called again with different data set to build new plots. The plots created with MATLAB can be exported in various file formats (e.g. .jpg, .png) to embed in Microsoft Word documents or PowerPoint slideshows.
MATLAB also contains interactive tools to explore and analyze data. For example, we can visualize data with one of the many plotting routines, zoom in to plots to take measurements, perform statistical calculations, fit curves to data and evaluate the obtained expression for a desired value.
MATLAB interacts with other applications (e.g. Microsoft Excel) and can be called from C code, C++ or Fortran programming language.

### Running MATLAB

To use MATLAB, it must be installed on your computer and you can start it just like you start any application on your system or you must have access to a network where it is available.

BCIT holds a Total Student Headcount (TSH) license for Mathworks software and this allows students to install MathWorks software on their personally-owned computers.

 Matlab download and installation instructions for BCIT students
For your install, choose the latest version available and install MATLAB, Curve Fitting Toolbox and Symbolic Math Toolbox.
In addition, MATLAB Online provides access to MATLAB from your web browser. Just log in to use MATLAB:
 Access MATLAB From Your Web Browser

### The MATLAB Desktop

When you start the MATLAB program, it displays the MATLAB desktop. The desktop is a set of tools (graphical user interfaces or GUIs) for managing files, variables, and applications associated with MATLAB. The first time you start MATLAB, the desktop appears with the default layout, as shown in the following illustration.

### Command Window

The Command Window is where we execute MATLAB commands. We enter statements at the Command Window prompt. The prompt can be any one of the following:
1. Trial>> indicates that the Command Window is in normal mode and the MATLAB license will expire after the trial period ends.
2. EDU>> indicates that the Command Window is in normal mode, in MATLAB Student Version.
3. >> indicates that the Command Window is in normal mode.

### Command History

The Command History is a log of the commands we have executed in the command window.

### Workspace

The workspace consists of a set of variables stored in memory during a MATLAB session. To open the Workspace browser, select Desktop > Workspace in the MATLAB desktop, or type

at the Command Window prompt.

### Current Folder

The Current Folder is like the Finder in Mac OS X or Windows Explorer in Windows operating systems and allows us to browse through the files and folders. The Current Folder also displays details about files in your current directory and within the hierarchy of the folders it contains.

### Tool Strip

The tool strip contains global tabs, Home, Plots and Apps. Contextual tabs become available when you need them.

The plots tab allows us to plot various types of graphs quickly and easily.

The apps tab gives quick access to interactive applications within MATLAB environment.

Layout button allows us to change the desktop layout or go back to the default configuration.

### Toolbar

The MATLAB toolbar provides on-screen buttons to access frequently used features such as, copy, paste, undo and redo.

### Keyboard shortcuts

MATLAB provides keyboard shortcuts for viewing a history of commands and listing contextual help.

### The Up Arrow Key

Suppose we want to enter the following equation:

But we mistakenly entered
MATLAB returns the following prompt:
Instead of retyping the equation, press the up arrow key, the mistakenly entered line is displayed. Using the left arrow key, move the cursor to the misspelled letter. Make the correction and press Return or Enter to execute the command.
Pressing the up arrow key repeatedly recalls the previously entered commands. Likewise, typing the first characters of previously entered line and pressing the up arrow key displays the full command line. To execute that line, simply press the Return or Enter key.

### The Tab Key

Suppose you forgot how to enter the square root command. Begin typing y=sq in the command prompt:

Then press the tab key and scroll down to sqrt. Select it and press Return or Enter key.

### The Semicolon Symbol

The semicolon symbol at the end of a line suppresses the screen output. This is useful when you want to keep your command window clean.

Type the following entry and press the Return key:
The following output is displayed:
Now, press the up arrow key to recall our initial entry
And insert a semicolon as follows:
No numerical result is displayed however MATLAB stores the value of y in the memory. We can recall the value y by simply typing y and pressing Return.

### MATLAB Help

MATLAB comes with three forms of online help: help, doc and demos.

### Help

Typing help in the Command Window lists all primary help topics. You can display a topic by clicking on the link.

Or if you know the command or function you need help with, you can type help followed by the command or function. For example to learn about clc command, type help clc at the command prompt:

Also try the following command:

 >> help clear

To learn about sine function, type  help sin at the command prompt:

### Doc

Obviously, to use help effectively, you need to know what you are looking for. Often times, especially when you first start learning an application, it is usually difficult to ask the right questions. In the case of MATLAB, doc command is generally better than help. If you type doc in the command prompt, MATLAB opens a browser from where you can obtain help easier:

Like using  help sin, try typing doc sin in the command prompt:

### Demos

You can learn more about MATLAB through demos by typing demo in the command prompt, a list of links to demos will open in Help Browser. Demos and online seminars are available at  product demos and online seminars.

### Useful Commands and Functions

For a detailed explanation and examples for each of the following type ‘help function’ (without quotes) at the MATLAB prompt.

### Summary of Key Points

1. MATLAB is a popular technical computing application and MathWorks offers a trial version of MATLAB on their website,
2. The MATLAB Desktop consists of Command Window, Command History, Workspace, Current Folder and Start Button,
3. The up/down arrow keys, the tab key and the semicolon are convenient tools to use the Command Window,
4. MATLAB features an online help, doc and demo,
5. Various commands and functions make MATLAB experience easier, for example, clc, clear and exit.


# Getting Started

## MATLAB Essentials

Learning a new skill, especially a computer program in this case, can be overwhelming. However, if we build on what we already know, the process can be handled rather effectively. In the preceding chapter we learned about MATLAB Graphical User Interface (GUI) and how to get help. Knowing the GUI, we will use basic math skills in MATLAB to solve linear equations and find roots of polynomials in this chapter.

### Basic Computation

### Mathematical Operators

The evaluation of expressions is accomplished with arithmetic operators as we use them in scientific calculators. Note the addtional operators shown in the table below:

### Operator Precedence

MATLAB allows us to build mathematical expressions with any combination of arithmetic operators. The order of operations are set by precedence levels in which MATLAB evaluates an expression from left to right. The precedence rules for MATLAB operators are shown in the list below from the highest precedence level to the lowest.

1. Parentheses ()
2. Power (^)
3. Multiplication (*), right division (/), left division (\)
4. Addition (+), subtraction (-)

### Mathematical Functions

MATLAB has all of the usual mathematical functions found on a scientific calculator including square root, logarithm, and sine.
Practice the following examples to familiarize yourself with the common mathematical functions. Be sure to read the relevant help and doc pages for functions that are not self explanatory.

### The format Function

The format function is used to control how the numeric values are displayed in the Command Window. The short format is set by default and the numerical results are displayed with 4 digits after the decimal point (see the examples above). The long format produces 15 digits after the decimal point.

### Variables

In MATLAB, a named value is called a variable. MATLAB comes with several predefined variables. For example, the name pi refers to the mathematical quantity π, which is approximately pi ans = 3.1416

### Declaring Variables

Variables in MATLAB are generally represented as matrix quantities. Scalars and vectors are special cases of matrices having size 1x1 (scalar), 1xn (row vector) or nx1 (column vector).

### Declaration of a Scalar

The term scalar as used in linear algebra refers to a real number. Assignment of scalars in MATLAB is easy, type in the variable name followed by = symbol and a number:

### Declaration of a Row Vector

Elements of a row vector are separated with blanks or commas.

### Declaration of a Column Vector

Elements of a column vector is ended by a semicolon:

### Declaration of a Matrix

Matrices are typed in rows first and separated by semicolons to create columns. Consider the examples below:

### Linear Equations

Systems of linear equations are very important in engineering studies. In the course of solving a problem, we often reduce the problem to simultaneous equations from which the results are obtained. As you learned earlier, MATLAB stands for Matrix Laboratory and has features to handle matrices. Using the coefficients of simultaneous linear equations, a matrix can be formed to solve a set of simultaneous equations.

### Polynomials

In the preceding section, we briefly learned about how to use MATLAB to solve linear equations. Equally important in engineering problem solving is the application of polynomials. Polynomials are functions that are built by simply adding together (or subtracting) some power functions. (see  Wikipedia).
The coeffcients of a polynominal are entered as a row vector beginning with the highest power and including the ones that are equal to 0.

### The polyval Function

We can evaluate a polynomial p for a given value of x using the syntax polyval(p,x) where p contains the coefficients of polynomial and x is the given number.

### The roots Function

Consider the following equation:
Probably you have solved this type of equations numerous times. In MATLAB, we can use the roots function to find the roots very easily.

### Splitting a Statement

You will soon find out that typing long statements in the Command Window or in the the Text Editor makes it very hard to read and maintain your code. To split a long statement over multiple lines simply enter three periods "..." at the end of the line and carry on with your statement on the next line.

### Comments

Comments are used to make scripts more "readable". The percent symbol % separates the comments from the code. Examine the following examples:

### Basic Operations

### Special Characters

### Summary of Key Points

1. MATLAB has the common functions found on a scientific calculator and can be operated in a similar way,
2. MATLAB can store values in variables. Variables are case sensitive and some variables are reserved by MATLAB (e.g. pi stores 3.1416),
3. Variable Editor can be used to enter or manipulate matrices,
4. The coefficients of simultaneous linear equations and polynomials are used to form a row vector. MATLAB then can be used to solve the equations,
5. The format function is used to control the number of digits displayed,
6. Three periods "..." at the end of the line is used to split a long statement over multiple lines,
7. The percent symbol % separates the comments from the code, anything following % symbol is ignored by MATLAB.


# Graphics

## Graphing with MATLAB

A picture is worth a thousand words, particularly visual representation of data in engineering is very useful. MATLAB has powerful graphics tools and there is a very helpful section devoted to graphics in MATLAB Help: Graphics. Students are encouraged to study that section; what follows is a brief summary of the main plotting features.

### Two-Dimensional Plots

### The plot Statement

Probably the most common method for creating a plot is by issuing plot(x, y) statement where function y is plotted against x.
Having variables assigned in the Workspace, x and y=sin(x) in our case, we can also select x and y, and right click on the selected variables. This opens a menu from which we choose plot(x,y). See the figure below.

### Annotating Plots

Graphs without labels are incomplete and labeling elements such as plot title, labels for x and y axes, and legend should be included. Using up arrow, recall the statement above and add the annotation commands as shown below.

Run the file and compare your result with the first one.

### Superimposed Plots

If you want to merge data from two graphs, rather than create a new graph from scratch, you can superimpose the two using a simple trick:

### Multiple Plots in a Figure

Multiple plots in a single figure can be generated with subplot in the Command Window. However, this time we will use the built-in Plot Tools. Before we initialize that tool set, let us create the necessary variables using the following script:
Note that the above script clears the command window and variable workspace. It also closes any open Figures. After running the script, we will have X1, Y1, Y2, Y3 and Y4 loaded in the workspace. Next, select File > New > Figure, a new Figure window will open. Click "Show Plot Tools and Dock Figure" on the tool bar.

Under New Subplots > 2D Axes, select four vertical boxes that will create four subplots in one figure. Also notice, the five variables we created earlier are listed under Variables.

After the subplots have been created, select the first supblot and click on "Add Data". In the dialog box, set X Data Source to X1 and Y Data Source to Y1. Repeat this step for the remaining subplots paying attention to Y Data Source (Y2, Y3 and Y4 need to be selected in the subsequent steps while X1 is always the X Data Source).

Next, select the first item in "Plot Browser" and activate the "Property Editor". Fill out the fields as shown in the figure below. Repeat this step for all subplots.

Save the figure as sinxcosx.fig in the current directory.

### Three-Dimensional Plots

3D plots can be generated from the Command Window as well as by GUI alternatives. This time, we will go back to the Command Window.

### The plot3 Statement

With the X1,Y1,Y2 and Y2 variables still in the workspace, type in plot3(X1,Y1,Y2) at the MATLAB prompt. A figure will be generated, click "Show Plot Tools and Dock Figure".

Use the property editor to make the following changes.

The final result should look like this:

Use help or doc commands to learn more about 3D plots, for example, image(x), surf(x) and mesh(x).

### Quiver or Velocity Plots

To plot vectors, it is useful to draw arrows so that the direction of the arrow points the direction of the vector and the length of the arrow is vector’s magnitude. However the standard plot function is not suitable for this purpose. Fortunately, MATLAB has quiver function appropriately named to plot arrows.
quiver(x,y,u,v) plots vectors as arrows at the coordinates (x,y) with components (u,v). The matrices x, y, u, and v must all be the same size and contain corresponding position and velocity components.

### Summary of Key Points

1. plot(x, y) and plot3(X1,Y1,Y2) statements create 2- and 3-D graphs respectively,
2. Plots at minimum should contain the following elements: title, xlabel, ylabel and legend,
3. Annotated plots can be easily generated with GUI Plot Tools,
4. quiver and quiver3 plots are useful for making vector diagrams.


# Introductory Programming

## Introductory Programming with MATLAB

MATLAB provides scripting and automation tools that can simplify repetitive computational tasks. For example, a series of commands executed in a MATLAB session to solve a problem can be saved in a script file called an m-file. An m-file can be executed from the command line by typing the name of the file or by pressing the run button in the built-in text editor tool bar.

### Script Files

A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m. By typing the filename at the command prompt, we can run the script and obtain results in the command window.

A sample m-file named ThermalConductivity.m is displayed in Text Editor below. Note the triangle (in green) run button in the tool bar, pressing this button executes the script in the command window.

Now let us see how an m-file is created and executed.

### The input Function

Notice that the script we have created above is not interactive and computes the total volume only for the variables defined in the m-file. To make this script interactive we will make some changes to the existing AcetyleneBottle.m by adding input function and save it as AcetyleneBottleInteractive.m.

The syntax for input is as follows:

### The disp Function

As you might have noticed, the output of our script is not displayed in a well-formatted fashion. Using disp, we can control how text or arrays are displayed in the command window. For example, to display a text string on the screen, type in disp('Hello world!'). This command will return our friendly greeting as follows: Hello world!

disp(variable) can be used to display only the value of a variable. To demonstrate this, issue the following command in the command window:
We have created a row vector with 5 elements. The following is displayed in the command window:
Now if we type in disp(b) and press enter, the variable name will not be displayed but its value will be printed on the screen:
The following example demonstrates the usage of disp function.

### The num2str Function

The num2str function allows us to convert a number to a text string. Basic syntax is str = num2str(A) where variable A is converted to a text and stored in str. Let's see how it works in AcetyleneBottleInteractiveDisp.m. Remember to save the file with a different name before editing it, for example, AcetyleneBottleInteractiveDisp1.m.

### The fopen and fclose Functions

The first command is used to open or create a file. The basic syntax for fopen is as follows:
For example, fo = fopen('output.txt', 'w'); opens or creates a new file named output.txt and sets the permission for writing. If the file already exists, it discards the existing contents.
fclose command is used to close a file. For example, if we type in fclose(fo);, we close the file that was created above.

### The fprintf Function

fprintf function writes formatted data to the computer monitor or a file. This command can be used to save the results of a calculation to a file. To do this, first we create or open an output file with fopen, second we issue the fprintf command and then we close the output file with fclose.

The simplified syntax for fprintf is as follows:
Upon running the file, the output.txt file will display the following:

### Loops

In programming, a loop executes a set of code a specified number of times or until a condition is met.

### For Loop

This loop iterates an index variable from an initial value using a specified increment to a final value and runs a set of code. The for loop syntax is the following:

    for loop_index=vector_statement
      code
      ...
      code
    end

### While Loop

Like the for loop, a while loop executes blocks of code over and over again however it runs as long as the test condition remains true. The syntax of a while loop is

    while test_condition
     code
     ...
     code
    end

### The diary Function

Instead of writing a script from scratch, we sometimes solve problems in the Command Window as if we are using a scientific calculator. The steps we perform in this fashion can be used to create an m-file. For example, the diary function allows us to record a MATLAB session in a file and retrieve it for review. Reviewing the file and by copying relevant parts of it and pasting them in to an m-file, a script can be written easily.

Typing diary at the MATLAB prompt toggles the diary mode on and off. As soon as the diary mode is turned on, a file called diary is created in the current directory. If you like to save that file with a specific name, say for example problem16, type

>> diary problem16.txt.

A file named problem16.txt will be created. The following is the content of a diary file called problem16.txt. Notice that in that session, the user is executing the four files we created earlier. The user's keyboard input and the resulting display output is recorded in the file. The session is ended by typing diary which is printed in the last line. This might be useful to create a record of your work to hand in with a lab or to create the beginnings of an m-file.

### Style Guidelines

Try to apply the following guidelines when writing your scripts:

1. Share your code or programs with others, consider adopting one of  Creative Commons or  GNU General Public License schemes
2. Include your name and contact info in the opening lines
3. Use comments liberally
4. Group your code and use proper indentation
5. Use white space liberally
6. Use descriptive names for your variables
7. Use descriptive names for your m-files

### Summary of Key Points

1. A script is a file containing a sequence of MATLAB statements. Script files have a filename extension of .m.
2. Functions such as input, disp and num2str can be used to make scripts interactive,
3. fopen, fprintf and fclose functions are used to create output files,
4. A for loop is used to repeat a specific block of code a definite number of times.
5. A while loop is used to repeat a specific block of code an indefinite number of times, until a condition is met.
6. The diary function is useful to record a MATLAB command window session from which an m-file can be easily created,
7. Various style guidelines covered here help improve our code.