In order to successfully complete this assignment, you must do the required reading, watch the provided videos, and complete all instructions. The embedded survey form must be entirely filled out and submitted on or before 11:59pm on the day before class. Students must come to class the next day prepared to discuss the material covered in this assignment.

Pre-Class Assignment: Vectors


1. Introducing the Course Textbooks

Student self guided learning through assigned readings are required for students to be successful. The course strives to use Open Educational Resources (OER) to help reduce financial burden on the students. To this end we have selected the following textbooks for reading assignments and supplemental examples:

DO NOT WORRY You will not be expected to read all three textbooks in this course! In fact, we try to keep the reading at a reasonable level and focus on problem solving. However, most students benefit from seeing material in multiple ways (Reading, Lecture, Practice, etc). Different students (and instructors) also prefer different writing styles and may learn better with different text (which is why we provide more than one).

Students are encouraged to review and become familiar with the style and layout of each text to act as a common reference for the course. If you get stuck on a topic try looking it up and reviewing it in one of the other texts. If you are still stuck you can search the Internet. Do not be afraid to also ask your instructor questions and come to office hours. That is why we are here!!! ✅ Do This: Download a copy of each textbooks onto your preferred reading device and review the Table of Contents in each text.

As you can see each textbook approaches Linear algebra in a slightly different way. This variety reflects the different philosophies of teaching and different ways of individual learning. One way to evaluate the focus of a particular textbook is to look at it's very first chapter. For Example:

  • The Beezer and Heffron texts start out with "Systems of linear Equations" and "Linear Systems." These topics are basically the same idea with the focus of defining linear systems as just sets of "linear combinations". Clearly this is a core concept and a good place to start.
  • The Boyd and Vandenberghe text choose to start with "Vectors". In linear algebra the "vector" is a mathematical tool for which all of the mechanics of the math is built. Again, not a bad place to start.

In the first few assignments this course we will be looking at both concepts. You will want to learn and be able to identify linear systems and how to represent them as vectors.

Question: Find three additional topics (Besides Linear Systems and Vectors) that seem to be common between the three textbooks. You can probably assume that these topics will be important to our course as well.

Put your answer to the above question here.


2. Today's Reading

Quite a bit of this pre-class assignment about vectors is motivated from Chapter 1 of the Stephen Boyd and Lieven Vandenberghe Applied Linear algebra book. This material may be review for some students and may be new for others. It is expected that students review the chapter to help them understand the material better.

Do This: Review Sections 1.1, 1.2 and 1.3 in Boyd and Vandenberghe and become familiar with the contents and the basic terminology. If you find this material is difficult make sure you take advantage of the survey at the end of this assignment to ask your instructor questions about things that are confusing.

HINT Many computers and smart phones have a "read to me feature". Some students find it helpful to download the pdf of the textbook and have the computer read to them out loud while they follow along.


3. Scalars, Vector and Tensors

The two primary mathematical entities that are of interest in linear algebra are the vector and the matrix. They are examples of a more general entity known as a tensor. The following video gives a basic introduction of scalars, vectors, and tensors. It is fine if you can not understand all of this video. We will learn most of it in this course.

NOTE: The terms vectors and tensors can get fairly confusing. For the purpose of this class, we will not use the term Tensor all that much. Instead we will treat everything as vectors (more on this later).

from IPython.display import YouTubeVideo
YouTubeVideo("ml4NSzCQobk",width=640,height=360, cc_load_policy=True)

Think of a scalar as a single number or variable that is an example of a 0th-order tensor. The following are all scalars:

$$ 1, \frac{1}{2}, 3.1416$$

Defining a scalar in python is easy. For example

a = 8
a
8

A vector, on the other hand, is an ordered list of values which we typically represent with lower case letters. Vectors are ordered arrays of single numbers and are an example of 1st-order tensor. The following are all vectors:

Row Vector: $$v = [ v_1, v_2, \dots, v_n ]$$ here $v_1, v_2, \dots, v_n$ are single numbers.

$$f = [1, 2, 3, 5, 8]$$

Here $f$ in the above example is a vector of numbers, and it is the common way we think of vectors.

Note, it is often more common to write vecors vertically. These are often called column vectors:

Column Vector: $$ v= \left[ \begin{matrix} v_1 \\ v_2 \\ \vdots \\ v_m \end{matrix} \right] $$ here $v_1, v_2, \dots, v_n$ are single numbers.

1.a: Introducing Vectors in Python

In Python, there are multiple ways to store a vector. Knowing how your vector is stored is very important (especially for debugging). Probably the easiest way to store a vector is using a list, which are created using standard square brackets as follows:

f = [1, 2, 3, 5, 8]
f
[1, 2, 3, 5, 8]

Another common way to store a vector is to use a tuple.

b = (2, 4, 8, 16)
b
(2, 4, 8, 16)

You can access a particular scalar in your Python object using its index. Remember that Python index starts counting at zero. For example, to get the fourth element in f and b vectors, we would use the following syntax:

print(f[3])
print(b[3])
5
16

Later in this course, we may discuss which data format is better (and introduce new ones). At this point let's not worry about it too much. You can always figure out a variable's data type using the type function. For example:

type(f)
list
type(b)
tuple

Finally, I am not sure if you will need this but always remember, it is easy to convert from a tuple to a list and vice versa:

#Convert tuple to list
b_list = list(b)
b_list
[2, 4, 8, 16]
#Convert list to tuple
f_list = tuple(f)
f_list
(1, 2, 3, 5, 8)

1.b: Vector size

A vector can be used to represent quantities or values in an application. The size (also called dimension or length) of the vector is the number of elements it contains. The size of the vector determines how many quantities are in the vector. We often refer to the size of a vector using the variable n. So an n-vector has n values. A 3-vector only has 3 values.

The length (len) function returns the size of a vector in Python:

len(f)
5
len(b)
4

1.c: Special Vectors

The following are special vectors with special names.

Standard Unit Vectors

Vectors with a single 1 and the rest of the values are zero have a special name called "Standard Unit Vectors". The number of different standard unit vectors there are is equal to the size of the vector. For example, a 3-vector has the following standard unit vectors:

$$ e_1 = \left[ \begin{matrix} 1 \\ 0 \\ 0 \end{matrix} \right] ,e_2 = \left[ \begin{matrix} 0 \\ 1 \\ 0 \end{matrix} \right], e_3 = \left[ \begin{matrix} 0 \\ 0 \\ 1 \end{matrix} \right] $$

Zero Vectors

Vectors with all values of zero also have a special name called "Zero Vectors". Typically we just use a zero to represent the zero vector. For example: $$ 0 = \left[ \begin{matrix} 0 \\ 0 \\ 0 \end{matrix} \right] $$

1.d: Examples

Vectors are used to represent all types of data that has structures. Here are some simple examples from the Boyd and Vandenberghe textbook:

Location and displacement

A 2-vector can be used to represent a position or location in a space. The first value is the distance in one direction (from the origin) and the second value is the distance in a different direction. Probably most students are famiar with the 2D Cartesian coordinate system where a location can be defined by two values in the x and y directions. Here is a simple scatter plot in python which show the concept:

%matplotlib inline
import matplotlib.pylab as plt
plt.rc('text', usetex=True)
p1 = [2, 1]
p2 = [1, 3]
p3 = [1, 1]

plt.plot(p1[0],p1[1],'*k')
plt.plot(p2[0],p2[1],'*k')
plt.plot(p3[0],p3[1],'*k')

## Add some labels (offset slightly)
plt.text(p1[0]+0.1,p1[1],'$p_1$')
plt.text(p2[0]+0.1,p2[1],'$p_2$')
plt.text(p3[0]+0.1,p3[1],'$p_3$')

## Fix the axis so you can see the points
plt.axis([0,4,0,4])
[0, 4, 0, 4]
Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x7fc7db7ae7b8> (for post_execute):
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110 
    111             # IPython >= 2

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/_pylab_helpers.py in draw_all(cls, force)
    130         for f_mgr in cls.get_all_fig_managers():
    131             if force or f_mgr.canvas.figure.stale:
--> 132                 f_mgr.canvas.draw_idle()
    133 
    134 atexit.register(Gcf.destroy_all)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in draw_idle(self, *args, **kwargs)
   1897         if not self._is_idle_drawing:
   1898             with self._idle_draw_cntx():
-> 1899                 self.draw(*args, **kwargs)
   1900 
   1901     def draw_cursor(self, event):

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1188 
   1189         for tick in ticks_to_draw:
-> 1190             tick.draw(renderer)
   1191 
   1192         # scale up the axis label box to also find the neighbors, not

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer)
    302 
    303         if self.label1On:
--> 304             self.label1.draw(renderer)
    305         if self.label2On:
    306             self.label2.draw(renderer)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in draw(self, renderer)
    752                     textrenderer.draw_tex(gc, x, y, clean_line,
    753                                           textobj._fontproperties, angle,
--> 754                                           mtext=mtext)
    755                 else:
    756                     textrenderer.draw_text(gc, x, y, clean_line,

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw_tex(self, gc, x, y, s, prop, angle, ismath, mtext)
    231         texmanager = self.get_texmanager()
    232 
--> 233         Z = texmanager.get_grey(s, size, self.dpi)
    234         Z = np.array(Z * 255.0, np.uint8)
    235 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in get_grey(self, tex, fontsize, dpi)
    418         alpha = self.grey_arrayd.get(key)
    419         if alpha is None:
--> 420             pngfile = self.make_png(tex, fontsize, dpi)
    421             X = _png.read_png(os.path.join(self.texcache, pngfile))
    422             self.grey_arrayd[key] = alpha = X[:, :, -1]

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in make_png(self, tex, fontsize, dpi)
    383             self._run_checked_subprocess(
    384                 ["dvipng", "-bg", "Transparent", "-D", str(dpi),
--> 385                  "-T", "tight", "-o", pngfile, dvifile], tex)
    386         return pngfile
    387 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex)
    296             report = subprocess.check_output(command,
    297                                              cwd=self.texcache,
--> 298                                              stderr=subprocess.STDOUT)
    299         except subprocess.CalledProcessError as exc:
    300             raise RuntimeError(

/opt/anaconda3/lib/python3.7/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    393 
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 
    397 

/opt/anaconda3/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    470         kwargs['stderr'] = PIPE
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:
    474             stdout, stderr = process.communicate(input, timeout=timeout)

/opt/anaconda3/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

/opt/anaconda3/lib/python3.7/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1520                         if errno_num == errno.ENOENT:
   1521                             err_msg += ': ' + repr(err_filename)
-> 1522                     raise child_exception_type(errno_num, err_msg, err_filename)
   1523                 raise child_exception_type(err_msg)
   1524 

FileNotFoundError: [Errno 2] No such file or directory: 'dvipng': 'dvipng'
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/opt/anaconda3/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

/opt/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/opt/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2047                         orientation=orientation,
   2048                         dryrun=True,
-> 2049                         **kwargs)
   2050                     renderer = self.figure._cachedRenderer
   2051                     bbox_artists = kwargs.pop("bbox_extra_artists", None)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    508 
    509         """
--> 510         FigureCanvasAgg.draw(self)
    511         renderer = self.get_renderer()
    512 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1188 
   1189         for tick in ticks_to_draw:
-> 1190             tick.draw(renderer)
   1191 
   1192         # scale up the axis label box to also find the neighbors, not

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer)
    302 
    303         if self.label1On:
--> 304             self.label1.draw(renderer)
    305         if self.label2On:
    306             self.label2.draw(renderer)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in draw(self, renderer)
    752                     textrenderer.draw_tex(gc, x, y, clean_line,
    753                                           textobj._fontproperties, angle,
--> 754                                           mtext=mtext)
    755                 else:
    756                     textrenderer.draw_text(gc, x, y, clean_line,

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw_tex(self, gc, x, y, s, prop, angle, ismath, mtext)
    231         texmanager = self.get_texmanager()
    232 
--> 233         Z = texmanager.get_grey(s, size, self.dpi)
    234         Z = np.array(Z * 255.0, np.uint8)
    235 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in get_grey(self, tex, fontsize, dpi)
    418         alpha = self.grey_arrayd.get(key)
    419         if alpha is None:
--> 420             pngfile = self.make_png(tex, fontsize, dpi)
    421             X = _png.read_png(os.path.join(self.texcache, pngfile))
    422             self.grey_arrayd[key] = alpha = X[:, :, -1]

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in make_png(self, tex, fontsize, dpi)
    383             self._run_checked_subprocess(
    384                 ["dvipng", "-bg", "Transparent", "-D", str(dpi),
--> 385                  "-T", "tight", "-o", pngfile, dvifile], tex)
    386         return pngfile
    387 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex)
    296             report = subprocess.check_output(command,
    297                                              cwd=self.texcache,
--> 298                                              stderr=subprocess.STDOUT)
    299         except subprocess.CalledProcessError as exc:
    300             raise RuntimeError(

/opt/anaconda3/lib/python3.7/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    393 
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 
    397 

/opt/anaconda3/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    470         kwargs['stderr'] = PIPE
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:
    474             stdout, stderr = process.communicate(input, timeout=timeout)

/opt/anaconda3/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

/opt/anaconda3/lib/python3.7/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1520                         if errno_num == errno.ENOENT:
   1521                             err_msg += ': ' + repr(err_filename)
-> 1522                     raise child_exception_type(errno_num, err_msg, err_filename)
   1523                 raise child_exception_type(err_msg)
   1524 

FileNotFoundError: [Errno 2] No such file or directory: 'dvipng': 'dvipng'
<Figure size 432x288 with 1 Axes>

Color

A 3-vector can represent a color, with its entries giving the Red, Green, and Blue (RGB) intensity values (often between 0 and 1). The vector (0,0,0) represents black, the vector (0, 1, 0) represents a bright pure green color, and the vector (1, 0.5, 0.5) represents a shade of pink.

The Python matplotlib library uses this type of vector to define colors. For example, the following code plots a point at the origin of size 10000 (the size of the circle, and the value does not have exact meaning here) and color c = (0,1,0). You can change the values for c and s to see the difference.

import warnings
warnings.filterwarnings("ignore")

c = (0, 1, 0)
plt.scatter(0,0, color=c, s=10000);
Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x7fc7db7ae7b8> (for post_execute):
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/opt/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in post_execute()
    107             def post_execute():
    108                 if matplotlib.is_interactive():
--> 109                     draw_all()
    110 
    111             # IPython >= 2

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/_pylab_helpers.py in draw_all(cls, force)
    130         for f_mgr in cls.get_all_fig_managers():
    131             if force or f_mgr.canvas.figure.stale:
--> 132                 f_mgr.canvas.draw_idle()
    133 
    134 atexit.register(Gcf.destroy_all)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in draw_idle(self, *args, **kwargs)
   1897         if not self._is_idle_drawing:
   1898             with self._idle_draw_cntx():
-> 1899                 self.draw(*args, **kwargs)
   1900 
   1901     def draw_cursor(self, event):

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1188 
   1189         for tick in ticks_to_draw:
-> 1190             tick.draw(renderer)
   1191 
   1192         # scale up the axis label box to also find the neighbors, not

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer)
    302 
    303         if self.label1On:
--> 304             self.label1.draw(renderer)
    305         if self.label2On:
    306             self.label2.draw(renderer)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in draw(self, renderer)
    752                     textrenderer.draw_tex(gc, x, y, clean_line,
    753                                           textobj._fontproperties, angle,
--> 754                                           mtext=mtext)
    755                 else:
    756                     textrenderer.draw_text(gc, x, y, clean_line,

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw_tex(self, gc, x, y, s, prop, angle, ismath, mtext)
    231         texmanager = self.get_texmanager()
    232 
--> 233         Z = texmanager.get_grey(s, size, self.dpi)
    234         Z = np.array(Z * 255.0, np.uint8)
    235 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in get_grey(self, tex, fontsize, dpi)
    418         alpha = self.grey_arrayd.get(key)
    419         if alpha is None:
--> 420             pngfile = self.make_png(tex, fontsize, dpi)
    421             X = _png.read_png(os.path.join(self.texcache, pngfile))
    422             self.grey_arrayd[key] = alpha = X[:, :, -1]

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in make_png(self, tex, fontsize, dpi)
    383             self._run_checked_subprocess(
    384                 ["dvipng", "-bg", "Transparent", "-D", str(dpi),
--> 385                  "-T", "tight", "-o", pngfile, dvifile], tex)
    386         return pngfile
    387 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex)
    296             report = subprocess.check_output(command,
    297                                              cwd=self.texcache,
--> 298                                              stderr=subprocess.STDOUT)
    299         except subprocess.CalledProcessError as exc:
    300             raise RuntimeError(

/opt/anaconda3/lib/python3.7/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    393 
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 
    397 

/opt/anaconda3/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    470         kwargs['stderr'] = PIPE
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:
    474             stdout, stderr = process.communicate(input, timeout=timeout)

/opt/anaconda3/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

/opt/anaconda3/lib/python3.7/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1520                         if errno_num == errno.ENOENT:
   1521                             err_msg += ': ' + repr(err_filename)
-> 1522                     raise child_exception_type(errno_num, err_msg, err_filename)
   1523                 raise child_exception_type(err_msg)
   1524 

FileNotFoundError: [Errno 2] No such file or directory: 'dvipng': 'dvipng'
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
/opt/anaconda3/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
    339                 pass
    340             else:
--> 341                 return printer(obj)
    342             # Finally look for special method names
    343             method = get_real_method(obj, self.print_method)

/opt/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
    242 
    243     if 'png' in formats:
--> 244         png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
    245     if 'retina' in formats or 'png2x' in formats:
    246         png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))

/opt/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
    126 
    127     bytes_io = BytesIO()
--> 128     fig.canvas.print_figure(bytes_io, **kw)
    129     data = bytes_io.getvalue()
    130     if fmt == 'svg':

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
   2047                         orientation=orientation,
   2048                         dryrun=True,
-> 2049                         **kwargs)
   2050                     renderer = self.figure._cachedRenderer
   2051                     bbox_artists = kwargs.pop("bbox_extra_artists", None)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    508 
    509         """
--> 510         FigureCanvasAgg.draw(self)
    511         renderer = self.get_renderer()
    512 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
    400         toolbar = self.toolbar
    401         try:
--> 402             self.figure.draw(self.renderer)
    403             # A GUI class may be need to update a window using this draw, so
    404             # don't forget to call the superclass.

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
   1647 
   1648             mimage._draw_list_compositing_images(
-> 1649                 renderer, self, artists, self.suppressComposite)
   1650 
   1651             renderer.close_group('figure')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
   2626             renderer.stop_rasterizing()
   2627 
-> 2628         mimage._draw_list_compositing_images(renderer, self, artists)
   2629 
   2630         renderer.close_group('axes')

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
    136     if not_composite or not has_images:
    137         for a in artists:
--> 138             a.draw(renderer)
    139     else:
    140         # Composite any adjacent images together

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
   1188 
   1189         for tick in ticks_to_draw:
-> 1190             tick.draw(renderer)
   1191 
   1192         # scale up the axis label box to also find the neighbors, not

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer)
    302 
    303         if self.label1On:
--> 304             self.label1.draw(renderer)
    305         if self.label2On:
    306             self.label2.draw(renderer)

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
     48                 renderer.start_filter()
     49 
---> 50             return draw(artist, renderer, *args, **kwargs)
     51         finally:
     52             if artist.get_agg_filter() is not None:

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/text.py in draw(self, renderer)
    752                     textrenderer.draw_tex(gc, x, y, clean_line,
    753                                           textobj._fontproperties, angle,
--> 754                                           mtext=mtext)
    755                 else:
    756                     textrenderer.draw_text(gc, x, y, clean_line,

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw_tex(self, gc, x, y, s, prop, angle, ismath, mtext)
    231         texmanager = self.get_texmanager()
    232 
--> 233         Z = texmanager.get_grey(s, size, self.dpi)
    234         Z = np.array(Z * 255.0, np.uint8)
    235 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in get_grey(self, tex, fontsize, dpi)
    418         alpha = self.grey_arrayd.get(key)
    419         if alpha is None:
--> 420             pngfile = self.make_png(tex, fontsize, dpi)
    421             X = _png.read_png(os.path.join(self.texcache, pngfile))
    422             self.grey_arrayd[key] = alpha = X[:, :, -1]

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in make_png(self, tex, fontsize, dpi)
    383             self._run_checked_subprocess(
    384                 ["dvipng", "-bg", "Transparent", "-D", str(dpi),
--> 385                  "-T", "tight", "-o", pngfile, dvifile], tex)
    386         return pngfile
    387 

/opt/anaconda3/lib/python3.7/site-packages/matplotlib/texmanager.py in _run_checked_subprocess(self, command, tex)
    296             report = subprocess.check_output(command,
    297                                              cwd=self.texcache,
--> 298                                              stderr=subprocess.STDOUT)
    299         except subprocess.CalledProcessError as exc:
    300             raise RuntimeError(

/opt/anaconda3/lib/python3.7/subprocess.py in check_output(timeout, *popenargs, **kwargs)
    393 
    394     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
--> 395                **kwargs).stdout
    396 
    397 

/opt/anaconda3/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    470         kwargs['stderr'] = PIPE
    471 
--> 472     with Popen(*popenargs, **kwargs) as process:
    473         try:
    474             stdout, stderr = process.communicate(input, timeout=timeout)

/opt/anaconda3/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    773                                 c2pread, c2pwrite,
    774                                 errread, errwrite,
--> 775                                 restore_signals, start_new_session)
    776         except:
    777             # Cleanup if the child failed starting.

/opt/anaconda3/lib/python3.7/subprocess.py in _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session)
   1520                         if errno_num == errno.ENOENT:
   1521                             err_msg += ': ' + repr(err_filename)
-> 1522                     raise child_exception_type(errno_num, err_msg, err_filename)
   1523                 raise child_exception_type(err_msg)
   1524 

FileNotFoundError: [Errno 2] No such file or directory: 'dvipng': 'dvipng'
<Figure size 432x288 with 1 Axes>

Just for fun, here is a little demo that lets you play with different color vectors:

%matplotlib inline
import matplotlib.pylab as plt
from ipywidgets import interact, fixed

def showcolor(red,green,blue):
    color=(red,green,blue)
    plt.scatter(0,0, color=color, s=20000);
    plt.axis('off');
    plt.show();
    return color

color = interact(showcolor, red=(0.0,1.0), green=(0.0,1.0), blue=(0.0,1.0));
(0.5, 0.5, 0.5)

1.e: Vector Addition

Two vectors of the same size can be added together by adding the corresponding elements, to form another vector of the same size, called the sum of the vectors. For example:

$$ \left[ \begin{matrix} 1 \\ 20 \end{matrix} \right] + \left[ \begin{matrix} 22 \\ -3 \end{matrix} \right] = \left[ \begin{matrix} 23 \\ 17 \end{matrix} \right] $$

Python Vector Addition

Here is where things get tricky in Python. If you try to add a list or tuple, Python does not do the vector addition as we defined above. In the following examples, notice that the two lists concatenate instead of adding by element:

## THIS IS WRONG
a = [1, 20]
b = [22,-3]
c = a+b
c
[1, 20, 22, -3]
## THIS IS WRONG
a = (1, 20)
b = (22,-3)
c = a+b
c
(1, 20, 22, -3)

To do proper vector math you need either use a special function (we will learn these) or loop over the list. Here is a very simplistic example:

a = (1, 20)
b = (22,-3)
c = []
for i in range(len(a)):
    c.append(a[i] + b[i])
c
[23, 17]

For fun, we can define this operation as a function in case we want to use it later:

def vecadd(a,b):
    if (len(a) != len(b)):
        raise Exception('Error - vector lengths do not match')
    c = []
    for i in range(len(a)):
        c.append(a[i] + b[i])
    return c
#Lets test it

vecadd(a,b)
[23, 17]

1.f: Scalar-Vector multiplication

You can also multiply a scalar by a vector, which is done by multiplying every element of the vector by the scalar.

$$ 3 \left[ \begin{matrix} 3 \\ -7 \\ 10 \end{matrix} \right] = \left[ \begin{matrix} 9 \\ -21 \\ 30 \end{matrix} \right] $$

Scalar-Vector Multiplication in Python

Again, this can be tricky in Python because Python lists do not do what we want. Consider the following example that just concatenates three copies of the vector.

##THIS IS WRONG## 
z = 3
a = [3,-7,10]
c = z*a
c
[3, -7, 10, 3, -7, 10, 3, -7, 10]

Again, in order to do proper vector math in Python you need either use a special function (we will learn these) or loop over the list.

Do This: See if you can make a simple function with a loop to multiply a scalar by a vector. Name your function sv_multiply and test it using the cells below:

#put your sv_multiply function here
#Test your function here
z = 3
a = [3,-7,10]
sv_multiply(z,a)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-22-3c1d0362d478> in <module>
      2 z = 3
      3 a = [3,-7,10]
----> 4 sv_multiply(z,a)

NameError: name 'sv_multiply' is not defined

4. Assignment wrap-up

Please fill out the form that appears when you run the code below. You must completely fill this out in order to receive credits for the assignment!

Direct Link to Survey Form

If you have trouble with the embedded form, please make sure you log on with your MSU account.

Assignment-Specific QUESTION: Are you able to get the sv_multiply function working in part 1 of this assignment?

Put your answer to the above question here

QUESTION: Summarize what you did in this assignment.

Put your answer to the above question here

QUESTION: What questions do you have, if any, about any of the topics discussed in this assignment after working through the jupyter notebook?

Put your answer to the above question here

QUESTION: How well do you feel this assignment helped you to achieve a better understanding of the above mentioned topic(s)?

Put your answer to the above question here

QUESTION: What was the most challenging part of this assignment for you?

Put your answer to the above question here

QUESTION: What was the least challenging part of this assignment for you?

Put your answer to the above question here

QUESTION: What kind of additional questions or support, if any, do you feel you need to have a better understanding of the content in this assignment?

Put your answer to the above question here

QUESTION: Do you have any further questions or comments about this material, or anything else that's going on in class?

Put your answer to the above question here

QUESTION: Approximately how long did this pre-class assignment take?

Put your answer to the above question here

from IPython.display import HTML
HTML(
"""
<iframe 
	src="https://cmse.msu.edu/cmse314-pc-survey" 
	width="100%" 
	height="1000px" 
	frameborder="0" 
	marginheight="0" 
	marginwidth="0">
	Loading...
</iframe>
"""
)

Congratulations, we're done!

To get credits for this assignment, you must fill out and submit the above survey form on or before the assignment due date.

Course Resources:

Writen by Dirk Colbry and Ming Yan, Michigan State University Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.