Chapter 4 Linear Algebra

Vectors


In [1]:
height = [70,  # inches,
          170, # pounds,
          40]  # years

In [2]:
grades = [95, # exam1,
          80, # exam2,
          75, # exam3,
          62] # exam4

In [3]:
def vector_add(v, w):
    '''adds corresponding elements'''
    return [v_i + w_i
            for v_i, w_i in zip(v, w)]

In [8]:
def vector_substract(v, w):
    """substracts corresponding elements"""
    return [v_i - w_i
            for v_i, w_i in zip(v, w)]

In [9]:
def vector_sum(vectors):
    """sums all corresponding elements"""
    result = vectors[0]                            # start with the first vector
    for vector in vectors[1: ]:                    # then loop over the others
        result = vector_add(result, vector)        # and add them to the result
    return result

In [13]:
def vector_sum2(vectors):
    return reduce(vector_add, vectors)

In [16]:
def scalar_multiply(c, v):
    """c is a number and v is a vector"""
    return [c * v_i for v_i in v]

In [18]:
def vector_mean(vectors):
    """compute the vector whose ith element is the mean 
    of the ith elements of the input vectors"""
    n = len(vectors)
    return scalar_multiply(1/n, vector_sum(vectors))

In [19]:
def dot(v, w):
    """v_1 * w_1 + v_2 * w_2 + ... + v_n * w_n"""
    return sum(v_i * w_i 
               for v_i, w_i in zip(v, w))

In [20]:
def sum_of_squares(v):
    """v_1 * v_1 + v_2 * v_2 + v_3 * v_3 + ... + v_n * v_n"""
    return dot(v, v)

In [21]:
import math

In [22]:
def magnitude(v):
    return math.sqrt(sum_of_squares(v))

In [23]:
def squared_distance(v, w):
    """(v_1 - w_1)^2 + (v_2 - w_2)^2 + ... + (v_n - w_n)^2"""
    return sum_of_squares(substract(v, w))

In [24]:
def distance1(v, w):
    return math.sqrt(squared_distance(v, w))

In [25]:
def distance2(v, w):
    return magnitude(substract(v, w))

Matrices


In [26]:
A = [[1, 2, 3],   # A has 2 rows and 3 columns
     [4, 5, 6]]

In [27]:
B = [[1, 2],      # B has 3 rows and 2 columns
     [3, 4],
     [5, 6]]

In [28]:
def shape(A):
    num_rows = len(A)
    num_cols = len(A[0]) if A else 0
    return num_rows, num_cols

In [29]:
def get_row(A, i):
    return A[i]

In [30]:
def get_column(A, j):
    return [A_i[j] for A_i in A]

In [33]:
def make_matrix(num_rows, num_cols, entry_fn):
    """returns a num_rows x num_cols matrix
    whose (i, j)th entry is generated by function entry_fn(i, j)"""
    return [[entry_fn(i, j) 
             for j in range(num_cols)]
             for i in range(num_rows)]

In [34]:
def is_diagonal(i, j):
    return 1 if i == j else 0

In [35]:
identity_matrix = make_matrix(5, 5, is_diagonal)
identity_matrix


Out[35]:
[[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]

For Further Exploration